tags:

views:

425

answers:

1

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

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'm running into a lot of errors, any help will be appreciated!

+2  A: 
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()
Thanks so much!
echoblaze