我需要一些帮助来弄清楚如何将文本文件中的单词拆分为列表。我可以使用这样的东西:
words = []
for line in open('text.txt'):
line.split()
words.append(line)
但是如果文件包含多行文本,它们会被分成子列表,例如
this is the first line
this is the second line
变成:
[['this', 'is', 'the', 'first', 'line'], ['this', 'is', 'the', 'second', 'line']]
如何使它们在同一个列表中?即
[['this', 'is', 'the', 'first', 'line', 'this', 'is', 'the', 'second', 'line']]
谢谢!
编辑: 该程序将打开多个文本文件,因此需要将每个文件中的单词添加到一个子列表中。所以如果一个文件有多行,这些行中的所有单词应该一起存储在一个子列表中。 即每个新文件开始一个新的子列表。
请您参考如下方法:
你可以使用列表推导式,像这样来展平单词列表
[word for words in line.split() for word in words]
这和写一样
result = []
for words in line.split():
for word in words:
result.append(word)
或者您可以使用 itertools.chain.from_iterable , 像这样
from itertools import chain
with open("Input.txt") as input_file:
print list(chain.from_iterable(line.split() for line in input_file))
