How to filter a file using a template to another file using Python?

I have a dictionary. I only want to take words containing a simple word pattern (ie "Cows") and write them to another file. Each line starts with a word and then a definition. I'm still very new to python, so I don't have a good understanding of the syntax, but the pseudocode in my head looks something like this:

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

      

I have a lot of bugs, any help would be appreciated!

0


a source to share


2 answers


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

      



+2


a source


using 'with open' and 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)

      

0


a source







All Articles