簡體   English   中英

正則表達式——Python【列表查詢】

[英]Regular expression - Python [list query]

我正在嘗試為此列表編寫一個正則表達式:

data= ["Fred is Deputy Manager. He is working for MNC.", "Rita is another employee in AC Corp."]

我想刪除所有以大寫字母開頭的單詞,但它不應該檢查每個句子的第一個單詞,即它不應該檢查 Fred、He 和 Rita。

output 應該是

Output-["Fred is. He is working for.", "Rita is another employee in."]

我嘗試尋找解決方案,但找不到任何相關代碼。 任何幫助,將不勝感激。

謝謝。

您將需要查找並刪除所有不遵循標點符號的大寫單詞,然后查找並刪除尾隨空格(此解決方案不是最干凈的,但它有效)。 列表推導也在這里派上用場。

import re

data = ["Fred is Deputy Manager. He is working for MNC.", "Rita is another employee in AC Corp."]
# find and replace all capital words that don't follow punctuation with ''
text = [re.sub(r'(?<!\.\s)(?!^)\b([A-Z]\w*(?:\s+[A-Z]\w*)*)', '', item) for item in data]
# find and remove all trailing spaces before periods
output = [re.sub(r'\s([?.!"](?:\s|$))', r'\1', item) for item in text]

>>> output
['Fred is. He is working for.', 'Rita is another employee in.']

首先,讓我為 python 3 的正則表達式文檔的無用表示歉意。 技術上講,所有回答這個問題的信息都可以在這里找到,但是您已經需要了解一些關於re如何工作的信息才能理解它。 話雖如此,希望這會給你一個幫助:

一個簡單的答案

這是您可以嘗試的一些代碼:

import re

data = ["Fred is Deputy Manager. He is working for MNC.", "Rita is another employee in AC Corp."]

matcher = re.compile("(?<![.])[ ][A-Z][A-z]*")
print([matcher.sub("",d) for d in data])
# prints: ['Fred is. He is working for.', 'Rita is another employee in.']

基本上,這會編譯一個正則表達式,它將匹配不帶句點的大寫單詞:

  • (?<.[.]) -> 如果前面有句點則不匹配
  • [ ][AZ][Az]* -> 任何大寫的單詞(有一個前導空格,以確保是否永遠不會匹配字符串中的第一個單詞)

然后,它將該正則表達式應用於列表中的每個字符串,並用空字符串替換匹配項: ""

一些限制

如果您的字符串曾經有雙空格或其他空白字符(如制表符或回車符)會破壞這一點。 您可以改用以下方法來解決此問題:

matcher = re.compile("(?<![.])\s+[A-Z][A-z]*")

其中\s+將匹配一個或多個空白字符

此外,如果您的琴弦以空格開頭,那也會破壞這一點。 您可以使用以下方法解決此問題:

print([matcher.sub("",d.strip(" ")) for d in data])

從字符串中刪除前導或尾隨空白字符。

暫無
暫無

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

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