【问题标题】:Python file regex matchingPython 文件正则表达式匹配
【发布时间】:2013-02-11 07:08:02
【问题描述】:

我试图在 python 中使用正则表达式从文件中提取某些单词,但我无法得到它。我的原始文件看起来像

List/VB 
[ the/DT flights/NNS ]
from/IN 

我希望输出是

List VB 
the DT
flights NNS
from IN 

我写了以下代码:

import re

with open("in.txt",'r') as infile, open("out.txt",'w') as outfile: 
    for line in infile:
        if (re.match(r'(?:[\s)?(\w\\\w)',line)):
            outfile.write(line)

【问题讨论】:

    标签: python regex match


    【解决方案1】:
    import re
    
    expr = re.compile("(([\w]+)\/([\w]+))", re.M)
    fp = open("file_list.txt",'r')
    lines = fp.read()
    fp.close()
    a = expr.findall(lines)
    for el in expr.findall(lines):
        print ' '.join(el[1:])
    

    输出:

    List VB
    the DT
    flights NNS
    from IN
    

    【讨论】:

    • 你应该制定你的答案。
    【解决方案2】:

    使用您提供的示例数据:

    >>> data = """List/VB 
    ... [ the/DT flights/NNS ]
    ... from/IN"""
    
    >>> expr = re.compile("(([\w]+)\/([\w]+))", re.M)
    >>> for el in expr.findall(data):
    >>>     print el[1], el[2]
    List VB
    the DT
    flights NNS
    from IN
    

    【讨论】:

    • 我的输出被打印为一个数组,我如何把它变成一个字符串?
    • 您的意思是要将 el[1] 和 el[2] 转换为单个字符串吗?在这种情况下,您可以执行 s = "%s %s" % el[1:3]
    猜你喜欢
    • 1970-01-01
    • 2016-07-01
    • 2013-09-22
    • 2022-12-11
    • 2020-10-09
    • 2016-08-08
    • 1970-01-01
    • 2011-05-15
    • 1970-01-01
    相关资源
    最近更新 更多