簡體   English   中英

Python 正則表達式刪除括號中的注釋或數字

[英]Python Regex remove comments or numbers in brackets

我正在嘗試使用正則表達式刪除行號和注釋,但它還不起作用:

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() 用於將單詞與從校車到校車的“-”連接起來也不起作用。

您可以使用這個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)))

Output:

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

細節:

  • re.sub(r'(\([^)]*\)|\[[^]]*\]|-)\s*', '', string) :刪除所有(...)[...]-后跟 0 個或多個空格的字符串
  • \b\w+ :匹配以單詞邊界開頭的 1+ 個單詞字符

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM