如何使用Python将模式过滤到另一个文件?

时间:2009-05-12 01:49:09

标签: python file-io

我有一本字典。我想只拿出包含一个简单的单词模式(即“cow”)的单词并将它们写入另一个文件。每行以一个单词开头,然后是定义。我仍然是python的新手,所以我对语法没有很好的把握,但是我头脑中的伪代码看起来像是:

infile = open('C:/infile.txt')
outfile = open('C:/outfile.txt')

pattern = re.compile('cow')

for line in infile:
  linelist = line.split(None, 2)
  if (pattern.search(linelist[1])
    outfile.write(listlist[1])

outfile.close()
infile.close()

我遇到了很多错误,任何帮助都会受到赞赏!

2 个答案:

答案 0 :(得分:2)

import re

infile  = open('C:/infile.txt')
outfile = open('C:/outfile.txt', 'w')

pattern = re.compile('^(cow\w*)')

for line in infile:
    found = pattern.match(line)
    if found:
        text = "%s\n" % (found.group(0))
        outfile.write(text)

outfile.close()
infile.close()

答案 1 :(得分:0)

使用'with open'并过滤

import re
pattern = re.compile('^(cow\w*)')

with open(outfile,"w") as fw:
  with open(infile,"r") as f:
    for outline in filter(lambda x: not pattern.match(x.strip()),f):
      fw.write(outline)