gpt4 book ai didi

python - 将多行文本文件拆分为一个列表?

转载 作者:太空宇宙 更新时间:2023-11-04 07:40:47 24 4
gpt4 key购买 nike

我需要一些帮助来弄清楚如何将文本文件中的单词拆分为列表。我可以使用这样的东西:

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))

关于python - 将多行文本文件拆分为一个列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21806214/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com