我的文件包含几行字符串:
[(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其他字符串.....放大)我能解决这些问题吗?
答案 0 :(得分:6)
没有正则表达式:
[p.split(')')[0] for p in s.split('(') if ')' in p]
输出:
['W', 'indo', 'ws ', 'XP', ', ', 'with ', 'the ', 'fragment ', 'enlar', 'ged ', 'for ', 'clarity ', 'on ', 'Fig. ']
答案 1 :(得分:3)
试试这个:
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. ']
答案 2 :(得分:2)
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)
答案 3 :(得分:0)
你的第一个问题是
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)
表示在括号内查找不是右括号的所有内容