【问题标题】:Function that calculates the total number of unique words in a textfile计算文本文件中唯一单词总数的函数
【发布时间】:2018-11-15 09:33:30
【问题描述】:

我正在使用 Python 3,我正在尝试编写一个函数来计算文本文件中唯一单词的总数。我在下面写了一些代码,但是当我运行它时,由于某种原因,我只得到 26 个唯一词,而实际上应该至少有 200 个。有人能发现我的代码有问题吗?

def countUniqueWords():
    words = open('phrases.txt')
    numberofUniqueWords = {}
    for word in words:
         try:
             numberofUniqueWords[word] += 1
         except KeyError:
             numberofUniqueWords[word] = 1
    print(len(numberofUniqueWords))

print(countUniqueWords())

【问题讨论】:

  • 看看你正在数的“单词”,你会发现它们是单个字母。
  • 每个word 都是文本文件中的一行。你应该先拆分它words.split()
  • 我想提两件事: 1. 你没有关闭你的文件。使用 .close()with 关键字。 2. 使用print(countUniqueWords()),您正在打印countUniqueWords 的返回值,但countUniqueWords 目前没有返回任何内容。

标签: python text-files


【解决方案1】:

您正在遍历文件中的章程,而不是文字。您需要使文件成为带有words = open('phrases.txt').read().split() 的单词列表。此外,您应该确保删除所有标点符号。

【讨论】:

    【解决方案2】:

    1) 使用集合而不是字典 2) words 只是一个字符串,你需要使用.split() 来获取字符串中的单词。

    def countUniqueWords():
        words = open('phrases.txt')
        uniqueWords = set(words.split())
        return len(uniqueWords)
    
    print(countUniqueWords())
    

    【讨论】:

    • 嗨!我尝试使用你的代码,但我不断收到错误'Python:AttributeError:'_io.TextIOWrapper'对象没有属性'split''
    • Nvm,明白了!非常感谢:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-17
    相关资源
    最近更新 更多