【问题标题】:Counting every word in a text file only once using python使用python仅计算文本文件中的每个单词一次
【发布时间】:2012-09-12 08:07:21
【问题描述】:

我正在编写一个小型 Python 脚本,用于完成课堂作业。该脚本读取一个文件并打印 10 个最频繁和最不频繁的单词及其频率。对于这个作业,一个单词被定义为 2 个或更多字母。我的词频工作得很好,但是任务的第三部分是打印文档中 unique 单词的总数。唯一词意味着计算文档中的每个词,只计算一次。

在不过多更改当前脚本的情况下,如何只计算一次文档中的所有单词?

附言。我使用的是 Python 2.6,所以请不要提及使用 collections.Counter

from string import punctuation
from collections import defaultdict
import re

number = 10
words = {}
total_unique = 0
words_only = re.compile(r'^[a-z]{2,}$')
counter = defaultdict(int)


"""Define words as 2+ letters"""
def count_unique(s):
    count = 0
    if word in line:
        if len(word) >= 2:
            count += 1
    return count


"""Open text document, read it, strip it, then filter it"""
txt_file = open('charactermask.txt', 'r')

for line in txt_file:
    for word in line.strip().split():
        word = word.strip(punctuation).lower()
        if words_only.match(word):
               counter[word] += 1


# Most Frequent Words
top_words = sorted(counter.iteritems(),
                    key=lambda(word, count): (-count, word))[:number] 

print "Most Frequent Words: "

for word, frequency in top_words:
    print "%s: %d" % (word, frequency)


# Least Frequent Words:
least_words = sorted(counter.iteritems(),
                    key=lambda (word, count): (count, word))[:number]

print " "
print "Least Frequent Words: "

for word, frequency in least_words:
    print "%s: %d" % (word, frequency)


# Total Unique Words:
print " "
print "Total Number of Unique Words: %s " % total_unique

【问题讨论】:

标签: python algorithm dictionary iteration defaultdict


【解决方案1】:

defaultdict 很棒,但它可能比您需要的更多。关于最常用词的部分,您将需要它。但是在没有那个问题的情况下,使用defaultdict 是矫枉过正的。在这种情况下,我建议改用set

words = set()
for line in txt_file:
    for word in line.strip().split():
        word = word.strip(punctuation).lower()
        if words_only.match(word):
               words.add(word)
num_unique_words = len(words)

现在words 只包含唯一词。

我发布这个只是因为你说你是 python 新手,所以我想确保你也知道sets。同样,出于您的目的,defaultdict 可以正常工作并且是合理的

【讨论】:

  • 太棒了!我不知道我可以为此目的使用一组
【解决方案2】:

计算keys 在您的counter 字典中的数量:

total_unique = len(counter.keys())

或者更简单地说:

total_unique = len(counter)

【讨论】:

  • 太棒了,它奏效了。谢谢!我只是在学习 Python,所以请原谅我发布了这么低级的问题。
猜你喜欢
  • 1970-01-01
  • 2018-08-25
  • 2023-03-29
  • 2014-11-04
  • 2017-08-14
  • 2022-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多