簡體   English   中英

Python正則表達式使用正則表達式刪除單詞

[英]Python regex removing word with regex

我是Python的新手,我想刪除({ / / })並替換為空格,以下示例

原句:

NULL ({ / / }) Regina ({ 4 p1 p2 / / }) Shueller ({ 5 p1 p2 / / }) works ({ / / }) for ({ / / }) Italy ({ 14 / / }) 's ({ 15 / / }) La ({ 16 / / }) Repubblica ({ 17 / / }) newspaper ({ 18 / / }) . ({ 38 / / })

轉換為此:

Regina Shueller works for Italy 's La Repubblica newspaper.

我已經嘗試過此代碼,但這不是我期望的

Sentence = re.sub(r'[({ / / })]',' ', sentence)

您嘗試的模式: r'[({ / / })]'意思是:

匹配({ /})

關鍵是要了解正則表達式語言 這些字符中的每一個在該語言中都有特殊的含義。

諸如r' \\({ [^/]*/ / }\\) '將與示例中的每個不同部分匹配。

您可以這樣做:

r'(\([^(]*\))'

現場演示

如果格式始終相同,則可以嘗試在去除標點符號后保留alpha值:

from string import punctuation
print(" ".join([w for w in s.split() if w.strip(punctuation).isalpha()]))

或使用正則表達式:

print(re.sub(r'\({.*?}\)',"",s))

您將刪除具有({})所有內容,而不管預期輸出中的內容是什么。

您可以使用

r'\s*(?:\(\{[^/]*/\s*/\s*}\)|NULL)\s*'

正則表達式演示

正則表達式說明

  • \\s* -零個或多個空格
  • (?:\\(\\{[^/]*/\\s*/\\s*}\\)|NULL) -兩種選擇, NULL\\(\\{[^/]*/\\s*/\\s*}\\)匹配...
    • \\( -開口圓括號
    • \\{ -開括號
    • [^/]* -除/以外的零個或多個字符
    • / -文字/
    • \\s* -零個或多個空格
    • /\\s* -同上。
    • } -右括號
    • \\) -封閉的圓括號
  • \\s* -零個或多個空格

請注意,單詞和標點之間的空格應分開處理。

Python演示

import re
p = r'\s*(?:\(\{[^/]*/\s*/\s*}\)|NULL)\s*'
test_str = "NULL ({ / / }) Regina ({ 4 p1 p2 / / }) Shueller ({ 5 p1 p2 / / }) works ({ / / }) for ({ / / }) Italy ({ 14 / / }) 's ({ 15 / / }) La ({ 16 / / }) Repubblica ({ 17 / / }) newspaper ({ 18 / / }) . ({ 38 / / })"
result = re.sub(p, " ", test_str)
print(result.strip())
# => Regina Shueller works for Italy 's La Repubblica newspaper .

暫無
暫無

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

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