[英]python - Return Text Between Parenthesis
我有文件包含幾行字符串寫為:
[(W)40(indo)25(ws )20(XP)111(, )20(with )20(the )20(fragment )20(enlar)18(ged )20(for )20(clarity )20(on )20(Fig. )] TJ
我只需要括號內的文字。 我嘗試使用以下代碼:
import re
readstream = open ("E:\\New folder\\output5.txt","r").read()
stringExtract = re.findall('\[(.*?)\]', readstream, re.DOTALL)
string = re.compile ('\(.*?\)')
stringExtract2 = string.findall (str(stringExtract))
但是輸出中不存在一些字符串(或文本),例如,對於上面的字符串,輸出中找不到單詞(with)。 字符串的排列也與文件不同,例如,對於上面的字符串(放大)和(ged),第二個(ged)出現在(放大)之前,例如:(ged其他字符串.....放大)我能解決這些問題嗎?
沒有正則表達式:
[p.split(')')[0] for p in s.split('(') if ')' in p]
輸出:
['W', 'indo', 'ws ', 'XP', ', ', 'with ', 'the ', 'fragment ', 'enlar', 'ged ', 'for ', 'clarity ', 'on ', 'Fig. ']
嘗試這個:
import re
readstream = open ("E:\\New folder\\output5.txt","r").read()
stringExtract2 = re.findall(r'\(([^()]+)\)', readstream)
readstream = r'[(W)40(indo)25(ws )20(XP)111(, )20(with )20(the )20(fragment )20(enlar)18(ged )20(for )20(clarity )20(on )20(Fig. )]'
['W', 'indo', 'ws ', 'XP', ', ', 'with ', 'the ', 'fragment ', 'enlar', 'ged ', 'for ', 'clarity ', 'on ', 'Fig. ']
findall看起來像你的朋友。 你不想要:
re.findall(r'\(.*?\)',readstream)
收益:
['(W)',
'(indo)',
'(ws )',
'(XP)',
'(, )',
'(with )',
'(the )',
'(fragment )',
'(enlar)',
'(ged )',
'(for )',
'(clarity )',
'(on )',
'(Fig. )']
編輯 :正如@vikramis所示,要刪除parens,請使用: re.findall(r'\\((.*?)\\)', readstream)
。 此外,請注意,通過以下方式修剪尾隨空格是很常見的(但不是在此請求):
re.findall(r'\((.*?) *\)', readstream)
你的第一個問題是
stringExtract = re.findall('\[(.*?)\]', readstream, re.DOTALL)
我不知道你為什么這樣做,我很確定你不想這樣做
試試這個
readstream = "[(W)40(indo)25(ws )20(XP)111(, )20(with )20(the )20(fragment )20(enlar)18(ged )20(for )20(clarity )20(on )20(Fig. )] TJ"
stringExtract = re.findall('\(([^)]+)\)', readstream, re.DOTALL)
其中說找到括號內的所有內容都不是右括號
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.