python - 将文本文件更改为列表

标签 python

我正在尝试使用 Python 进行编码。我一直在寻找能够满足我的问题的答案,但所有答案似乎都比我需要的更复杂。我正在尝试打开一个文本文件并列出出现的每个唯一单词。我最终会添加一个计数器来记录每个单词出现的次数,但我还没有做到这一点,我只是在使用的单词列表方面寻求帮助。当我尝试调用该函数时,出现“builtins.NameError:名称“文件名”未定义”错误。因此,我什至看不到代码是否有效。我将非常感谢任何帮助。

    def computeWordFrequencies(filename):
        f = open ('filename.txt','r') # Opens the file as read
        line = f.readlines() # Reads the file
        L[0] = [] # Lists the unique words that occur in the file
        L[1] = [] # Upon completion, this variable will count 
        #the number of appearances of each word
        for line in f:
        L[0].append(line.split())
        L[0] = uniqueExtend(L[0])
    return(L[0])

最佳答案

如果您只想要独特的单词,实际上以下方法会起作用:

set( open('filename.txt').read().split() )

这会创建文件中所有单词的列表 (open('filename.txt').read().split())。然后它由此创建一个集合 (set( ... ))。集合类似于列表,但仅保存每个项目中的一个,因此这样做会自动使所有条目都是唯一的。

请注意,这没有考虑标点符号、大小写等。

关于python - 将文本文件更改为列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28977575/

相关文章:

python - Pandas pivot_table 多个 aggfunc

python - 在Elasticsearch文档线程中更新数组是否安全?

python - 如何从用户输入的 float 中删除一组字符 - Python

python - 对数图中的负轴

Python:如何不仅打印运行for语句后的最终值,还打印中间输出?

python - 如何启用 python 的 json 包来编码 attrdict.AttrDict 对象?

python - 为什么不应该在 python 中使用 list.sort

python - gschemas.compiled 架构是否特定(我可以将其与我的 python 库一起提供)吗?

python - 无法导入随机python

python - 将对象转储到 JSON 文件的两种方法有什么区别吗?