【问题标题】:Python Regex remove comments or numbers in bracketsPython Regex 删除括号中的注释或数字
【发布时间】:2021-04-15 18:13:09
【问题描述】:

我正在尝试使用正则表达式删除行号和 cmets,但它现在还不起作用:

import re
string = """(1) At what time.!? [asdf] School-
(2) bus. So late, already.!? [ghjk]"""

#res = re.sub(r"[\(\[].*?[\)\]]", "", string)

res = re.sub("(\d+) ","", res)
res = re.sub("[.*]","", res)
res = re.sub(r"-\s","", res)
res = re.sub(r"[^\w\säüöß]","", res)
res = re.sub("-\n","", res)
print(res.split())

所以我试图用我的#commented 行删除括号 () 和 [] 中的任何内容,但后来我被困在每行开头的空白处。 然后我决定把它拆分出来,想出了五个 re.sub 方法。

结果应该是这样的:

['At', 'what', 'time', 'Schoolbus', 'So', 'late', 'already']

我对没有被删除的行号感到困惑,尽管它们在 () 中并且应该消失了。然后导致我的 res.sub() 用于将带有“-”的单词从校车连接到校车也无法正常工作。

【问题讨论】:

    标签: python regex


    【解决方案1】:

    您可以使用这个sub + findall 解决方案:

    import re
    
    string = """(1) At what time.!? [asdf] School-
    (2) bus. So late, already.!? [ghjk]"""
    
    print (re.findall(r'\b\w+(?:-\w+)*', re.sub(r'(\([^)]*\)|\[[^]]*\]|-)\s*', '', string)))
    

    输出:

    ['At', 'what', 'time', 'Schoolbus', 'So', 'late', 'already']
    

    详情:

    • re.sub(r'(\([^)]*\)|\[[^]]*\]|-)\s*', '', string):删除所有 (...)[...]- 后跟 0 个或多个空格的字符串
    • \b\w+: 匹配以单词边界开头的 1+ 个单词字符

    【讨论】:

      猜你喜欢
      • 2021-01-08
      • 2020-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-28
      • 1970-01-01
      • 1970-01-01
      • 2016-08-15
      相关资源
      最近更新 更多