如果匹配列表中的项目,则替换字符串中的项目 [英] replace item in a string if it matches an item in the list

查看:60
本文介绍了如果匹配列表中的项目,则替换字符串中的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果它们与列表匹配,我正在尝试从字符串中删除单词.

I am trying to remove words from a string if they match a 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, '')

它产生以下输出:

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

我希望它删除与列表匹配的全部字样.

I want it to remove all the words matching the list.

推荐答案

您没有保留x.replace()的结果.请尝试以下操作:

You are not keeping the result of x.replace(). Try the following instead:

for tag in tags:
    x = x.replace(tag, '')
print x

请注意,您的方法匹配任何子字符串,而不仅仅是完整的单词.例如,它将删除RUN LOLA RUN中的LOL.

Note that your approach matches any substring, and not just full words. For example, it would remove the LOL in RUN LOLA RUN.

解决此问题的一种方法是将每个标签括在一对r'\b'字符串中,并寻找产生的正则表达式. r'\b'仅在单词边界匹配:

One way to address this would be to enclose each tag in a pair of r'\b' strings, and look for the resulting regular expression. The r'\b' would only match at word boundaries:

for tag in tags:
    x = re.sub(r'\b' + tag + r'\b', '', x)

这篇关于如果匹配列表中的项目,则替换字符串中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆