【问题标题】:replace item in a string if it matches an item in the list如果匹配列表中的项目,则替换字符串中的项目
【发布时间】:2012-03-12 20:52:28
【问题描述】:

我正在尝试从字符串中删除与列表匹配的单词。

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

我希望它删除所有与列表匹配的单词。

【问题讨论】:

  • LOL 盗版过滤器喜欢它。

标签: python list replace


【解决方案1】:

您没有保留x.replace() 的结果。请尝试以下方法:

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

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

解决此问题的一种方法是将每个标签括在一对r'\b' 字符串中,然后查找生成的regular expression。 r'\b' 只会匹配单词边界:

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

【讨论】:

  • 谢谢!有什么方法可以删除括号“[],()”?当我将它们添加到列表时,我得到一个无效的表达式错误。
  • @koogee:我建议对特殊字符使用原始的非正则表达式方法([、]、(、) 等)。
  • 将 '[' ']' 添加到列表中会得到 File "test3.py", line 23, in <module> x = re.sub(r'\b' + tag + r'\b', '', x) File "/usr/lib64/python2.7/re.py", line 151, in sub return _compile(pattern, flags).sub(repl, string, count) File "/usr/lib64/python2.7/re.py", line 244, in _compile raise error, v # invalid expression sre_constants.error: unexpected end of regular expression
【解决方案2】:

str.replace() 方法不会就地更改字符串——字符串在 Python 中是不可变的。您必须在每次迭代中将x 绑定到replace() 返回的新字符串:

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

注意if 语句是多余的; str.replace() 如果找不到匹配项,则不会执行任何操作。

【讨论】:

    【解决方案3】:

    使用您的变量tags 和x,您可以这样使用:

    output = reduce(lambda a,b: a.replace(b, ''), tags, x)
    

    返回:

    'How I Met Your Mother 7x17 (-) [] - Mon, 20 Feb 2012'
    

    【讨论】:

    • 不可变方法 :-)
    【解决方案4】:

    (1)x.replace(tag, '') 不会修改x,而是返回一个带有替换的new 字符串。

    (2) 为什么每次迭代都要打印?

    您可以做的最简单的修改是:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-11
      • 2021-03-27
      • 1970-01-01
      • 1970-01-01
      • 2019-03-09
      • 2020-07-18
      • 1970-01-01
      • 2015-05-25
      相关资源
      最近更新 更多