【问题标题】:How to delete the text within brackets using re.compile and re.findall?如何使用 re.compile 和 re.findall 删除括号内的文本?
【发布时间】:2019-10-29 03:58:57
【问题描述】:

我想删除括号之间的文字(包括括号)。此文本存储在列表中。我还想存储输出文本(在新列表中不带括号)。

我尝试使用:

es = ["49,331,076","23,136,275","139,500 (est.)","124,000","522 (ranked 23 of 137)"]
length=len(es)
regex = re.compile(".*?\((.*?)\)")
for x in range(length):
    listy.append(re.findall(regex, es[p]))
    p=p+1

但是,这将返回括号之间的文本。

预期结果:

"[49,331,076, 23,136,275, 139,500, 124,000, 522]"

我得到的结果:

"[], [], [est.], [u'ranked 18 of 137']"

【问题讨论】:

  • 你知道正则表达式不能处理多个嵌套括号的理论吗?
  • 为什么答案不被接受?您需要更多帮助吗?有什么问题?

标签: python regex list beautifulsoup


【解决方案1】:

您可以将re.sub\([^()]*\) 模式一起使用:

import re
es = ["49,331,076","23,136,275","139,500 (est.)","124,000","522 (ranked 23 of 137)"]
regex = re.compile(r"\([^()]*\)")
listy = []
for x in es:
    listy.append(regex.sub('', x).strip())
# Or, instead of the two lines above use a list comprehension:
# listy = [regex.sub('', x).strip() for x in es]
print(listy) # => ['49,331,076', '23,136,275', '139,500', '124,000', '522']

Python demo

请注意,使用for x in es: 循环遍历列表项更容易,无需获取其长度然后使用计数器跟踪当前项。使用列表推导式更符合 Pythonic,[regex.sub('', x).strip() for x in es]

\([^()]*\) 模式匹配 (,然后是除 () 之外的任何 0+ 字符,然后是 )。如果两者之间可以有(,请使用\(.*?\)\([^)]*\)

【讨论】:

  • 当找到( 时增加一个计数器,找到) 时减少一个简单的循环,当计数器再次为零时,删除子字符串,会更好吗?
【解决方案2】:

我只想对匹配项做一个sub()

import re
es = ["49,331,076","23,136,275","139,500 (est.)","124,000","522 (ranked 23 of 137)"]

length=len(es)
regex = re.compile("\(.+\)")
cleaned_es = [regex.sub('', val) for val in es]
print(cleaned_es)

您也可以输入 strip() 来删除任何尾随空格:

cleaned_es = [regex.sub('', val).strip() for val in es]

这会给你:

['49,331,076', '23,136,275', '139,500', '124,000', '522']

【讨论】:

    猜你喜欢
    • 2016-08-24
    • 1970-01-01
    • 2013-11-17
    • 2012-03-10
    • 1970-01-01
    • 1970-01-01
    • 2021-06-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多