koo*_*gee 4 python replace list
我试图从字符串中删除单词,如果它们匹配列表.
x = "How I Met Your Mother 7x17 (HDTV-LOL) [VTV] - Mon, 20 Feb 2012"
tags = ['HDTV', 'LOL', 'VTV', 'x264', 'DIMENSION', 'XviD', '720P', 'IMMERSE']
print x
for tag in tags:
if tag in x:
print x.replace(tag, '')
Run Code Online (Sandbox Code Playgroud)
它产生这个输出:
How I Met Your Mother 7x17 (HDTV-LOL) [VTV] - Mon, 20 Feb 2012
How I Met Your Mother 7x17 (-LOL) [VTV] - Mon, 20 Feb 2012
How I Met Your Mother 7x17 (HDTV-) [VTV] - Mon, 20 Feb 2012
How I Met Your Mother 7x17 (HDTV-LOL) [] - Mon, 20 Feb 2012
Run Code Online (Sandbox Code Playgroud)
我希望它删除匹配列表的所有单词.
NPE*_*NPE 13
你没有保留结果x.replace().请尝试以下方法:
for tag in tags:
x = x.replace(tag, '')
print x
Run Code Online (Sandbox Code Playgroud)
请注意,您的方法匹配任何子字符串,而不仅仅是完整的单词.例如,它会删除LOLin RUN LOLA RUN.
解决此问题的一种方法是将每个标记包含在一对r'\b'字符串中,并查找生成的正则表达式.将r'\b'只会匹配的单词边界:
for tag in tags:
x = re.sub(r'\b' + tag + r'\b', '', x)
Run Code Online (Sandbox Code Playgroud)
该方法str.replace()不会更改字符串 - 字符串在Python中是不可变的.您必须绑定x到replace()每次迭代中返回的新字符串:
for tag in tags:
x = x.replace(tag, "")
Run Code Online (Sandbox Code Playgroud)
请注意,该if陈述是多余的; str.replace()如果找不到匹配项,将不会做任何事情.