Slo*_*ner 3 python regex dictionary list-comprehension python-3.x
以下Python 3代码循环遍历字符串列表,并使用正则表达式替换每个字符串中的一些文本.
这里的字符串很简单,但在实际情况下它们可能更复杂,数量更多,因此我决定使用re.sub()而不是str.replace().
all = ("this line has no hits",
"a letter to tom from peter",
"today bonny went to school",
"harry made some cake")
for myitem in all:
newitem = re.sub("harry","sally",myitem)
newitem = re.sub("tom","jerry",newitem)
newitem = re.sub("bonny","clyde",newitem)
print(newitem)
Run Code Online (Sandbox Code Playgroud)
这似乎按预期工作:
>>> this line has no hits
a letter to jerry from peter
today clyde went to school
sally made some cake
>>>
Run Code Online (Sandbox Code Playgroud)
在现实生活中会有大量的字符串,这会产生一堆乱码.我认为通过在a中定义正则表达式对dict并使用列表理解,可能有更简洁,更Pythonic的方法.所以我尝试了这个:
mydict = {'harry':'sally','tom':'jerry','bonny':'clyde'}
newall = [re.sub(i, mydict[i], j) for i in mydict for j in all]
print(newall)
Run Code Online (Sandbox Code Playgroud)
这不起作用,因为它不返回带有替换文本的字符串列表,但我不明白为什么它不起作用.
我的问题是:
(注意,我可能已经错过了这里显而易见的事情,因为我只看了几天Python;我的背景是R和Perl.)
列表理解有两个列表是令人讨厌的.它们容易出错并且难以阅读.为什么不简单地使用两个循环?:
all = ("this line has no hits",
"a letter to tom from peter",
"today bonny went to school",
"harry made some cake")
mydict = {'harry':'sally','tom':'jerry','bonny':'clyde'}
output = []
for line in all:
for search, replace in mydict.items():
line = re.sub(search, replace, line)
output.append(line)
print(output)
Run Code Online (Sandbox Code Playgroud)
['这条线没有命中','来自彼得的一封致杰里的信','今天克莱德上学','sally做了一些蛋糕']