鉴于此文件:
$ cat words.txt
line1 word1 word2
line2 word3 word4
line3 word5 word6
如果您一次只想要一个单词(忽略文件中空格与换行符的含义):
with open('words.txt','r') as f:
for line in f:
for word in line.split():
print(word)
印刷:
line1
word1
word2
line2
...
word6
同样,如果您想将文件展平为文件中单个单词的平面列表,您可以执行以下操作:
with open('words.txt') as f:
flat_list=[word for line in f for word in line.split()]
>>> flat_list
['line1', 'word1', 'word2', 'line2', 'word3', 'word4', 'line3', 'word5', 'word6']
它可以创建与第一个示例相同的输出print '\n'.join(flat_list)
...
或者,如果您想要文件每一行中单词的嵌套列表(例如,从文件创建行和列矩阵):
with open('words.txt') as f:
matrix=[line.split() for line in f]
>>> matrix
[['line1', 'word1', 'word2'], ['line2', 'word3', 'word4'], ['line3', 'word5', 'word6']]
如果您想要一个正则表达式解决方案,这将允许您在示例文件中过滤wordN
与lineN
键入单词:
import re
with open("words.txt") as f:
for line in f:
for word in re.findall(r'\bword\d+', line):
# wordN by wordN with no lineN
或者,如果您希望它是带有正则表达式的逐行生成器:
with open("words.txt") as f:
(word for line in f for word in re.findall(r'\w+', line))