簡體   English   中英

正則表達式替換Python

[英]Regular expression substitution Python

我對此有麻煩。 我正在嘗試更好地處理RE,但無法正常工作。 如果有另一個字符串,我有一個要刪除的字符串列表。

這是排除列表:

exclusionList = ['\+','of','<ET>f.','to','the','<L>L.</L>','f.','in','and','see','a','<L>Fr.</L>','as','<ET>ad.','<ET>a.','<PS>v.</PS></XR>',
             'from','<CF>ab</CF>','or','n.','<L>OFr.</L>','pple.','away','was','with','off,','pa.','on','is','cf.','stem','ad.','which',
             'by','action','ppl.','Cf.','but','<L>Gr.</L>','be','after','=','The','form','for','an','<XR><RX>prec.</RX></XR>',
             '<PS>a.</PS></XR>','<L>Eng.</L>','<PS>pref.</PS>','also','L.</L>','<XR><XL>a-</XL>','<XR><XL>-ing</XL><HO>1</HO></XR>.</ET>',
             'vb.','See','In','<L>OE.</L>','used','it','see','this','not','<PS>prep.</PS><HO>1</HO></XR>','has','a','so','early','s']

這就是我用來刪除這些單詞的內容:

first_word = re.sub(r'\b'+exclusionList[a]+'\b', '',first_word)

其中第一個單詞是從文本文件讀取的字符串。 我知道這將很簡單,但我只是不太了解如何很好地使用RE。

謝謝

我只能猜測,但可能您想要這樣的東西:

pattern = r'\b({})\b'.format('|'.join(map(re.escape, exclusionList)))
first_word = re.sub(pattern, '', first_word)

請注意,我在對單詞進行轉義,因此它們將在字面上進行匹配,而不是被解釋為正則表達式(它們似乎不是正則表達式)。

這應該一下子就完成了:

exclusionRegex = r'\b(' + '|'.join(re.escape(word) for word in exclusionList) + r')\b'
first_word = re.sub(exclusionRegex, '', first_word)

編輯 :這是我的測試腳本:

import re

exclusionList = ['\+','of','<ET>f.','to','the','<L>L.</L>','f.','in','and','see','a','<L>Fr.</L>','as','<ET>ad.','<ET>a.','<PS>v.</PS></XR>',
             'from','<CF>ab</CF>','or','n.','<L>OFr.</L>','pple.','away','was','with','off,','pa.','on','is','cf.','stem','ad.','which',
             'by','action','ppl.','Cf.','but','<L>Gr.</L>','be','after','=','The','form','for','an','<XR><RX>prec.</RX></XR>',
             '<PS>a.</PS></XR>','<L>Eng.</L>','<PS>pref.</PS>','also','L.</L>','<XR><XL>a-</XL>','<XR><XL>-ing</XL><HO>1</HO></XR>.</ET>',
             'vb.','See','In','<L>OE.</L>','used','it','see','this','not','<PS>prep.</PS><HO>1</HO></XR>','has','a','so','early','s']

exclusionRegex = r'\b(' + '|'.join(re.escape(word) for word in exclusionList) + r')\b'
first_word = 'This is a test of the regex'
print re.sub(exclusionRegex, '', first_word)

這是輸出:

這個測試正則表達式

暫無
暫無

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

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