python - 在python中读取文件后返回单词列表

标签 python string list

我有一个名为 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/

相关文章:

python - 将路径重新定位到新根目录的最Pythonic方法

c++ - 如何测试字符串是否是有效的 C++(ish) 表达式?

string - 从 Haskell 中的字符串中删除额外的引号

language-agnostic - 有索引链表的已知实现吗?

python - 如何使用 Django 创建特定的 if 条件模板标签?

python - Athena 查询在控制台中有效,但在 sagemaker 中不适用于 boto3 客户端(将 csv 转换为表格)

python - IndexError:列表索引超出范围,face_recognition

string - 我需要检查一个字符串是否与 postgresql 中的模式匹配

python - 使用字符串作为名称导入文件

python - 将数组转换为字符串