我有一个小的 Python 脚本,用于计算 .txt 文档中前 10 个最常用的词、10 个最不常用的词和总词数。根据作业,一个词被定义为2个字母或更多。我有 10 个最常见的单词和 10 个最不常见的单词打印得很好,但是当我尝试打印文档中的单词总数时,它会打印所有单词的总数,包括单个字母单词(例如“a” )。我怎样才能得到单词总数来只计算有 2 个或更多字母的单词?
这是我的脚本:
from string import *
from collections import defaultdict
from operator import itemgetter
import re
number = 10
words = {}
total_words = 0
words_only = re.compile(r'^[a-z]{2,}$')
counter = defaultdict(int)
"""Define function to count the total number of words"""
def count_words(s):
unique_words = split(s)
return len(unique_words)
"""Define words as 2 letters or more -- no single letter words such as "a" """
for word in words:
if len(word) >= 2:
counter[word] += 1
"""Open text document, strip it, then filter it"""
txt_file = open('charactermask.txt', 'r')
for line in txt_file:
total_words = total_words + count_words(line)
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 Words: %s" % total_words
我不是 Python 专家,这是针对我目前正在学习的 Python 课程的。在这项作业中,我的代码的整洁性和正确的格式对我不利,如果可能的话,有人还能告诉我这段代码的格式是否被认为是“好的做法”吗?