【问题标题】:python - Return Text Between Parenthesispython - 在括号之间返回文本
【发布时间】:2015-01-31 08:18:20
【问题描述】:

我的文件包含几行字符串,写成:

[(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 other strings..... enlar) How我可以解决这些问题吗?

【问题讨论】:

  • 在陈述模式时始终使用原始字符串

标签: python regex python-2.7


【解决方案1】:

findall 在这里看起来像你的朋友。你不就是想要吗:

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

返回:

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

编辑: 正如@vikramis 所示,要删除括号,请使用:re.findall(r'\((.*?)\)', readstream)。另外,请注意,使用以下内容修剪尾随空格很常见(但此处未要求):

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

【讨论】:

    【解决方案2】:

    没有正则表达式:

    [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(')')返回的列表中的第一个元素。所以它会从当前的“(”到下一个“)”中获取所有内容,并忽略括号外的所有内容。
    【解决方案3】:

    你的第一个问题是

    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)
    

    表示找到括号内不是右括号的所有内容

    【讨论】:

    • 这会为我返回(W,),而不是字符串中括号内的所有文本。
    【解决方案4】:

    试试这个:

    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. ']
    

    【讨论】:

      猜你喜欢
      • 2011-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-02
      相关资源
      最近更新 更多