这应该有效:
>>> with open('abc') as f, open('output.txt', 'w') as f2:
... for line in f:
... for word in line.split(): #split the line at whitespaces
... word = word.strip("'") # strip out `'` from each word
... if len(word) == 2: #if len(word) is 2 then write it to file
... f2.write(word + '\n')
print open('output.txt').read()
4m
t0
it
使用regex
:
>>> import re
>>> with open('abc') as f, open('output.txt', 'w') as f2:
for line in f:
words = re.findall(r"'(.{2})'",line)
for word in words:
f2.write(word + '\n')
...
>>> print open('output.txt').read()
4m
t0
it