Python文件正则表达式匹配

时间:2013-02-25 23:54:09

标签: python regex match

我试图在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)

1 个答案:

答案 0 :(得分: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