1.修改函数print_file_stats,使其也打印文件中不同的单词总数。
2.修改函数print_file_stats,使其打印文件中单词的平均长度。
3.罕用语(hapax hegomenon)是在文件中只出现过一次的单词。请修改函数print_file_stats,使其打印罕用语总数。
4。前面说过,文件bill.txt中出现频率最高的10个单词都是功能词,如the和and。我们通常对这些单词不感兴趣,因此我们可创建一个排除词(stop word)集合,其中包含要忽略的所有单词。
在函数print_file_stats中新增一个名为stop_words的变量,如下所示:
stop_words = {'the', 'and', 'i', 'to', 'of', 'a', 'you', 'my', 'that', 'in'}
当然,你可根据自已的喜好修改排除词集合。现在,修改程序的代码,在计算所有统计数据时,都将stop_list中的单词排除在外。
5.(较难)函数print_file_stats将一个文件名作为输入,并将整个文件都读取到一个字符串变量中。这种做法的问题在于,如果文件很大,将整个文件都放在一个字符串变量中将占用大量内存。
另一种做法是以每次一行的方式读取文件,这样占用的内存通常少得多。
请编写一个名为print_file_stats_lines的新函数,其功能与print_file_stats完全相同,但逐行读取输入文件。使用相同的文件调用这两个函数时,它们的输出应该相同。
#countwordpractice.py
from time import strftime, localtime #时间相关的模块
import datetime #获取系统时间
#包含所有要保留的字符的集合
keep = {'a', 'b', 'c', 'd', 'e',
'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o',
'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y',
'z', ' ', '-', "'"}
def normalize(s):
"""Convert s to a normalized string.
"""
result = ''
for c in s.lower():
if c in keep:
result +=c
return result
def make_freq_dict(s):
"""Returns a dictionary whose keys are the words of s,
dnd whose values are the counts of those words.
"""
s = normalize(s)
words = s.split()
d = {}
for w in words:
if w in d: #看到w出现过?
d[w] += 1
else:
d[w] = 1
return d
def print_file_stats(fname):
"""Print statistics for the given file.
"""
start = datetime.datetime.now()
s = open(fname, 'r').read()
num_chars = len(s) #在规范化s之前计算
num_lines = s.count('\n') #在规范化s之前计算
d = make_freq_dict(s)
#print("print_file_stats======d===========", d)
num_words = sum(d[w] for w in d) #计算s包含多少个单词
#创建一个列表,其中的元素由出现次数和单词组成的元组
#并按出现次数从高到低排列
lst = [(d[w], w) for w in d]
lst.sort()
lst.reverse()
print("The file '%s' has: " % fname)
print(" %s characters" % num_chars)
print(" %s lines" % num_lines)
print(" %s words" % num_words)
end = datetime.datetime.now()
print(end - start) #打印运行时间
#return
print("\nThe top 10 most frequent words are:")
i = 1 # i为列表元素编号
for count, word in lst[:10]:
print('%2s. %4s %s' % (i, count, word))
i += 1
#1.打印文件中不同的单词总数。
nWordCount = len(lst)
print("1.打印文件中不同的单词总数 word count = %d" % nWordCount)
#print(lst)
#2.打印文件中单词的平均长度。
#[(12, 'the'), (10, 'modules'), (8, 'of'), (6, 'are')...]
#(count, word)是一组键值对
# | |
# 12 the
nCharCount = 0
for count, word in lst:
#print('%2s. %4s %s' % (i, count, len(word)))
#i += 1
nCharCount += len(word)
print("2.打印文件中单词的平均长度 average word length = %d" % (nCharCount / nWordCount))
#罕用语(hapax hegomenon)是在文件中只出现过一次的单词。
#请修改函数print_file_stats,使其打印罕用语总数
hapax = 0
for count, word in lst:
if count > 1: #单词数大于1过滤掉
continue
hapax += 1
print("3.打印文件中打印罕用语总数hapax hegomenon = %d" % hapax)
#4。前面说过,文件bill.txt中出现频率最高的10个单词都是功能词,如the和and。
#我们通常对这些单词不感兴趣,因此我们可创建一个排除词(stop word)集合,
#其中包含要忽略的所有单词。在函数print_file_stats中新增一个名为stop_words的变量,
#如下所示:
stop_words = {'the', 'and', 'i', 'to', 'of', 'a', 'you', 'my', 'that', 'in'}
#当然,你可根据自已的喜好修改排除词集合。现在,修改程序的代码,在计算所有统计数据时,
#都将stop_list中的单词排除在外。
validWord = [] #创建空的列表
j = 0
for count, word in lst:
if not (word in stop_words):
#print('validWord[%3s]= %4s %s' % (j, count, word))
j += 1
validWord.append(word) #如果单词不在stop_words里,添加到有效单词中
print("4.有效单词个数 validWard = %d" % len(validWord))
"""
5.(较难)函数print_file_stats将一个文件名作为输入,并将整个文件都读取到一个字符串变量中。
这种做法的问题在于,如果文件很大,将整个文件都放在一个字符串变量中将占用大量内存。
另一种做法是以每次一行的方式读取文件,这样占用的内存通常少得多。
请编写一个名为print_file_stats_lines的新函数,其功能与print_file_stats完全相同,
但逐行读取输入文件。使用相同的文件调用这两个函数时,它们的输出应该相同。
"""
def print_file_stats_lines(fname):
"""Print statistics for the given file.
"""
#with open(fname, 'r') as file_object:
# contents = file_object.read()
# print(contents)
start = datetime.datetime.now()
#print(strftime("%Y-%m-%d %H:%M:%S", localtime())) # 打印当前时间
#逐行读取
num_lines = 0
num_chars = 0
d = {}
s = ''
with open(fname, 'r') as file_object:
lines = file_object.readlines()
for line in lines:
#print("line[%3s]======%s" % (num_lines, line))
num_lines += 1
num_chars += len(line)
#d += make_freq_dict(line)
#s = normalize(line)
for c in line.lower():
if c in keep:
s += c
words = s.split()
for w in words:
if w in d: #看到w出现过?
d[w] += 1
else:
d[w] = 1
#print("print_file_stats_lines=====d===========", d)
num_words = sum(d[w] for w in d) #计算s包含多少个单词
#print("num_words===========%d" % num_words)
#创建一个列表,其中的元素由出现次数和单词组成的元组
#并按出现次数从高到低排列
lst = [(d[w], w) for w in d]
lst.sort()
lst.reverse()
print("The file '%s' has: " % fname)
print(" %s characters" % num_chars)
print(" %s lines" % num_lines)
print(" %s words" % num_words)
end = datetime.datetime.now()
print(end - start) #打印运行时间
#return
print("\nThe top 10 most frequent words are:")
i = 1 # i为列表元素编号
for count, word in lst[:10]:
print('%2s. %4s %s' % (i, count, word))
i += 1
#1.打印文件中不同的单词总数。
nWordCount = len(lst)
print("1.打印文件中不同的单词总数 word count = %d" % nWordCount)
#print(lst)
#2.打印文件中单词的平均长度。
#[(12, 'the'), (10, 'modules'), (8, 'of'), (6, 'are')...]
#(count, word)是一组键值对
# | |
# 12 the
nCharCount = 0
for count, word in lst:
#print('%2s. %4s %s' % (i, count, len(word)))
#i += 1
nCharCount += len(word)
print("2.打印文件中单词的平均长度 average word length = %d" % (nCharCount / nWordCount))
#罕用语(hapax hegomenon)是在文件中只出现过一次的单词。
#请修改函数print_file_stats,使其打印罕用语总数
hapax = 0
for count, word in lst:
if count > 1: #单词数大于1过滤掉
continue
hapax += 1
print("3.打印文件中打印罕用语总数hapax hegomenon = %d" % hapax)
#4。前面说过,文件bill.txt中出现频率最高的10个单词都是功能词,如the和and。
#我们通常对这些单词不感兴趣,因此我们可创建一个排除词(stop word)集合,
#其中包含要忽略的所有单词。在函数print_file_stats中新增一个名为stop_words的变量,
#如下所示:
stop_words = {'the', 'and', 'i', 'to', 'of', 'a', 'you', 'my', 'that', 'in'}
#当然,你可根据自已的喜好修改排除词集合。现在,修改程序的代码,在计算所有统计数据时,
#都将stop_list中的单词排除在外。
validWord = [] #创建空的列表
j = 0
for count, word in lst:
if not (word in stop_words):
#print('validWord[%3s]= %4s %s' % (j, count, word))
j += 1
validWord.append(word) #如果单词不在stop_words里,添加到有效单词中
print("4.有效单词长度 length = %d" % len(validWord))
运行结果: