Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/356.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python-返回括号之间的文本_Python_Regex_Python 2.7 - Fatal编程技术网

python-返回括号之间的文本

python-返回括号之间的文本,python,regex,python-2.7,Python,Regex,Python 2.7,我有一个文件包含几行字符串,写为: [(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 =

我有一个文件包含几行字符串,写为:

[(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)。此外,字符串的排列方式与文件不同,例如,对于上面的字符串(enlar)和(ged),第二个字符串(ged)出现在(enlar)之前,例如:(ged其他字符串……enlar)如何解决这些问题?

您的第一个问题是

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)

上面写着找到括号内所有不是结束括号的东西findall看起来像你的朋友。难道你不想:

re.findall(r'\(.*?\)',readstream)
返回:

['(W)',
 '(indo)',
 '(ws )',
 '(XP)',
 '(, )',
 '(with )',
 '(the )',
 '(fragment )',
 '(enlar)',
 '(ged )',
 '(for )',
 '(clarity )',
 '(on )',
 '(Fig. )']
编辑: 如@vikramis所示,要删除paren,请使用:
re.findall(r'\(.*)\),readstream)
。另外,请注意,通常(但此处不要求)使用以下内容修剪尾随空格:

re.findall(r'\((.*?) *\)', readstream)
试试这个:

import re

readstream = open ("E:\\New folder\\output5.txt","r").read()
stringExtract2 = re.findall(r'\(([^()]+)\)', readstream)
输入: 输出: 没有regexp:

[p.split(')')[0] for p in s.split('(') if ')' in p]
输出:

['W', 'indo', 'ws ', 'XP', ', ', 'with ', 'the ', 'fragment ', 'enlar', 'ged ', 'for ', 'clarity ', 'on ', 'Fig. ']

在声明模式时始终使用原始字符串。对于我来说,此返回的不是字符串中括号内的所有文本。很抱歉将其挖掘出来,[0]用于什么?它获取由
p.split('))
返回的列表中的第一个元素。因此,它从当前“(“到下一个”)”中提取所有内容,并忽略括号外的内容。
[p.split(')')[0] for p in s.split('(') if ')' in p]
['W', 'indo', 'ws ', 'XP', ', ', 'with ', 'the ', 'fragment ', 'enlar', 'ged ', 'for ', 'clarity ', 'on ', 'Fig. ']