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

0 投票
2 回答
2775 浏览
提问于 2025-04-15 11:31

我有一个字典。我想从中找出只包含一个简单单词模式(比如“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

使用 'with open' 和 filter

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)
2

在编程中,有时候我们会遇到一些问题,比如代码运行不正常或者出现错误。这些问题可能是因为我们写的代码有bug,或者是因为我们没有正确理解某些概念。

当你在编程时,如果发现代码不工作,首先要冷静下来,仔细检查你的代码。可以从以下几个方面入手:

  • 检查拼写错误:有时候一个小小的拼写错误就会导致代码无法运行。
  • 查看变量的值:在代码运行时,看看你的变量是否有你预期的值。
  • 使用调试工具:很多编程环境都有调试工具,可以帮助你逐步运行代码,找出问题所在。

记住,编程是一个不断学习和解决问题的过程,不要气馁!

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()

撰写回答