【发布时间】:2016-04-08 04:43:30
【问题描述】:
以下 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)
这似乎按预期工作:
>>> this line has no hits
a letter to jerry from peter
today clyde went to school
sally made some cake
>>>
在现实生活中会有大量的字符串,这会导致代码块混乱。我认为通过在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)
这不起作用,因为它不会返回带有替换文本的字符串列表,但我不明白为什么它不起作用。
我的问题是:
- 我在上面的例子中做错了什么?
- 是否有更好的方法来解决涉及长字符串的大量替换问题?
(请注意,我可能错过了这里的明显内容,因为我只研究 Python 几天;我的背景是 R 和 Perl。)
【问题讨论】:
-
print(newall)的输出是什么? -
没关系,您的解决方案所做的是
all中的项目和mydict中的项目的某种笛卡尔积。查看解决方案的答案:) -
顺便说一句,
all是一个你可能不想覆盖的 python 内置函数。
标签: python regex python-3.x dictionary list-comprehension