[英]Python split words before ':' character but not time structure
我正在嘗試使用正則表達式對字符進行Split
:
但是,我不想split
時間結構,例如15:46:00。
我所擁有的所有信息都位於for
循環內,並且來自於抓取pdf文件。
因此,使用此代碼:
for item in result:
for key in keyHeaders:
if key in item.encode('utf-8'):
item = item.replace(key, '')
if ':' in item:
item = item.replace(':', ':\n')
輸出:
15:
46:
00
State:
NY
Phone:
x-xxx-xxx
我如何使用正則表達式或非正則表達式來split
單詞,而不split
由:
字符連接的數字。
我試過了,但是什么也沒發生。 實際上,它不會拆分任何內容。
for item in result:
for key in keyHeaders:
if key in item.encode('utf-8'):
item = item.replace(key, '')
lines = re.compile(r'(?<!\\d\\d):(?!\\d\\d)') # expect split words before ':'
if item == re.findall(lines, item):
item = item.replace(':', ':\n')
輸出:
15:46:00
State:NY
Phone:x-xxx-xxx
謝謝你的支持!
您的代碼有兩個問題。 首先,您使用了原始字符串,然后仍然將'\\\\ d'上的反斜杠加倍,將其改為'\\ d'。 另一個問題是您將整個項目與re.findall返回的值進行比較。 如果您的正則表達式正確,則re.findall將為非日期的項目僅返回“:”,因此您應與“:”進行比較,否則僅返回任何內容。
對於相對簡單的匹配,您的正則表達式也過於復雜。 我會用類似的東西:
if not re.findall(r'\d\d:\d\d:\d\d', item):
item = item.replace(':', ':\n')
還有可能更簡單的方法可以通過re.sub或re.split來完成整個工作,但這應該可以幫助您克服當前的障礙。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.