如何使用模式将一个文件过滤到另一个使用Python的文件?
我有一本字典。我只想将包含简单单词模式(即“cow”)的单词写入另一个文件。每行以一个单词开头,然后是定义。我对python还是非常陌生,所以我对语法没有很好的掌握,但我脑海中的伪代码看起来像:如何使用模式将一个文件过滤到另一个使用Python的文件?,python,file-io,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
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()
我遇到了很多错误,任何帮助都将不胜感激 使用“打开”和过滤器
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()
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)
johannix的答案在技术上是正确的,但当像grep这样的现有工具已经存在时,您不应该编写自己的程序:grep“^cow”infle.txt>outfile.txtA“很多错误”没有帮助。一两个特定的错误是有帮助的。