0

我正在尝试在 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)
4

2 回答 2

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
于 2013-02-26T00:03:30.547 回答
0
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
于 2013-09-21T21:07:01.700 回答