Reputation: 11626
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!
Upvotes: 0
Views: 2789
Reputation: 485
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)
Upvotes: 0
Reputation: 29658
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()
Upvotes: 2