[英]Searching and capturing a character using regular expressions Python
在經歷“ Python挑戰”中的問題之一時,我嘗試如下解決該問題:
讀取具有字符的文本文件中的輸入,如下所示:
DQheAbsaMLjTmAOKmNsLziVMenFxQdATQIjItwtyCHyeMwQTNxbbLXWZnGmDqHhXnLHfEyvzxMhSXzd
BEBaxeaPgQPttvqRvxHPEOUtIsttPDeeuGFgmDkKQcEYjuSuiGROGfYpzkQgvcCDBKrcYwHFlvPzDMEk
MyuPxvGtgSvWgrybKOnbEGhqHUXHhnyjFwSfTfaiWtAOMBZEScsOSumwPssjCPlLbLsPIGffDLpZzMKz
jarrjufhgxdrzywWosrblPRasvRUpZLaUbtDHGZQtvZOvHeVSTBHpitDllUljVvWrwvhpnVzeWVYhMPs
kMVcdeHzFZxTWocGvaKhhcnozRSbWsIEhpeNfJaRjLwWCvKfTLhuVsJczIYFPCyrOJxOPkXhVuCqCUgE
luwLBCmqPwDvUPuBRrJZhfEXHXSBvljqJVVfEGRUWRSHPeKUJCpMpIsrV.......
我需要的是瀏覽此文本文件,並選擇所有僅用小寫字母包圍的小寫字母,每側僅包含三個大寫字母。
我為執行上述操作而編寫的python腳本如下:
import re
pattern = re.compile("[a-z][A-Z]{3}([a-z])[A-Z]{3}[a-z]")
f = open('/Users/Dev/Sometext.txt','r')
for line in f:
result = pattern.search(line)
if result:
print result.groups()
f.close()
上面給出的腳本不是返回capture(小寫字母列表),而是返回所有符合正則表達式條件的文本塊,例如
aXCSdFGHj
vCDFeTYHa
nHJUiKJHo
.........
.........
有人可以告訴我我到底在做什么錯嗎? 除了遍歷整個文件之外,還有其他方法可以對整個文件運行正則表達式搜索嗎?
謝謝
我建議使用環視:
(?<=[A-Z]{3})(?<![A-Z].{3})([a-z])(?=[A-Z]{3})(?!.{3}[A-Z])
重疊匹配不會有問題。
說明:
(?<=[A-Z]{3}) # assert that there are 3 uppercase letters before the current position
(?<![A-Z].{3}) # assert that there is no uppercase letter 4 characters before the current position
([a-z]) # match a lowercase character (all characters in the example are ASCII)
(?=[A-Z]{3}) # assert that there are 3 uppercase letter after the current position
(?!.{3}[A-Z]) # assert that there is no uppercase letter 4 characters after the current position
將result.groups()
更改為result.group(1)
,您將只獲得單個字母匹配項。
您的代碼的第二個問題是它將無法在一行上找到多個結果。 因此, re.findall
使用re.search
您還需要re.findall
或re.finditer
。 findall
將返回字符串或字符串元組,而finditer
返回匹配對象。
這是我處理相同問題的地方:
import urllib
import re
pat = re.compile('[a-z][A-Z]{3}([a-z])[A-Z]{3}[a-z]')
print ''.join(pat.findall(urllib.urlopen(
"http://www.pythonchallenge.com/pc/def/equality.html").read()))
請注意, re.findall
和re.finditer
返回不重疊的結果。 因此,當對字符串'aBBBcDDDeFFFg'
使用上述模式與re.findall
搜索時,您唯一的匹配項將是'c'
,而不是'e'
。 幸運的是,此Python挑戰問題不包含此類示例。
import re
with open('/Users/Dev/Sometext.txt','r') as f:
tokens = re.findall(r'[a-z][A-Z]{3}([a-z])[A-Z]{3}[a-z]', f.read())
for token ins tokens:
print token
findall
是:
返回字符串中模式的所有非重疊匹配項,作為字符串列表。 從左到右掃描該字符串,並以找到的順序返回匹配項。 如果該模式中存在一個或多個組,則返回一個組列表;否則,返回一個列表。 如果模式包含多個組,則這將是一個元組列表。 空匹配項將包括在結果中,除非它們碰到另一個匹配項的開頭。
也許是re
模塊中最有用的功能。
read()函數將整個文件讀入大字符串。 如果您需要將正則表達式與整個文件進行匹配,這將特別有用。
警告 :根據文件的大小,您可能希望像第一種方法一樣逐行遍歷文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.