我有一个名为 test.txt
的文本文件。我想阅读它并返回文件中所有单词的列表(删除换行符)。
这是我当前的代码:
def read_words(test.txt):
open_file = open(words_file, 'r')
words_list =[]
contents = open_file.readlines()
for i in range(len(contents)):
words_list.append(contents[i].strip('\n'))
return words_list
open_file.close()
运行这段代码会产生这个列表:
['hello there how is everything ', 'thank you all', 'again', 'thanks a lot']
我希望列表看起来像这样:
['hello','there','how','is','everything','thank','you','all','again','thanks','a','lot']
最佳答案
根据文件的大小,这似乎很简单:
with open(file) as f:
words = f.read().split()
关于python - 在python中读取文件后返回单词列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13259288/