Python 如果字符串中的项与列表中的项匹配,则替换该项
我试图删除字符串中匹配列表的单词Python 如果字符串中的项与列表中的项匹配,则替换该项,python,list,replace,Python,List,Replace,我试图删除字符串中匹配列表的单词 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, '') 它产生以下输出
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, '')
它产生以下输出:
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
我希望它删除与列表匹配的所有单词。您没有保留
x.replace()的结果。
。请尝试以下操作:
for tag in tags:
x = x.replace(tag, '')
print x
请注意,您的方法匹配任何子字符串,而不仅仅是完整的单词。例如,它将删除RUN LOLA RUN
中的LOL
解决这个问题的一种方法是将每个标记包含在一对r'\b'
字符串中,并查找结果。r'\b'
仅在单词边界处匹配:
for tag in tags:
x = re.sub(r'\b' + tag + r'\b', '', x)
方法
str.replace()
不会就地更改字符串——字符串在Python中是不可变的。您必须在每次迭代中将x
绑定到replace()
返回的新字符串:
for tag in tags:
x = x.replace(tag, "")
请注意,if
语句是多余的str.replace()
(2) 为什么每次迭代都要打印
您可以做的最简单的修改是:
for tag in tags:
x = x.replace(tag, '')
使用变量标记
和x
,您可以使用:
output = reduce(lambda a,b: a.replace(b, ''), tags, x)
返回:
'How I Met Your Mother 7x17 (-) [] - Mon, 20 Feb 2012'
哈哈,我喜欢。谢谢!有没有办法去掉括号“[],()”?当我将它们添加到列表中时,我得到了一个无效的表达式错误。@koogee:我建议对特殊字符使用原始的非正则表达式方法([
,]
,(
,)
),等等)。将“['']”添加到列表中,会得到文件“test3.py”,第23行,在x=re.sub(r'\b'+tag+r'\b','',x)文件中“/usr/lib64/python2.7/re.py”,第151行,在sub-return\u compile(pattern,flags).sub(repl,string,count)文件“/usr/lib64/python2.7/re.py”,第244行,在-u-compile-raiser-error中,v#无效的表达式sre_常量。错误:正则表达式的意外结尾
不可变方法:-)