电脑任意文件夹中新建words.txt, 包含以下内容: to be or not to be to be or not to be to be or not to be not or to be to be 请分别用readline(和readlines0两种方法编写代码实 现以下功能: 口 读取words.txt中的内容,创建字典统计文本内容 中出现的词语及其对应的频次,打印该字典; 口 找到该文本文件中出现频次最高的词语,打印该词语和它出现的频次。
时间: 2024-02-28 17:57:28 浏览: 74
好的,下面是Python代码实现:
使用readline方法:
```
word_dict = {}
with open('words.txt', 'r') as f:
line = f.readline()
while line:
words = line.split()
for word in words:
if word in word_dict:
word_dict[word] += 1
else:
word_dict[word] = 1
line = f.readline()
print(word_dict)
max_word = max(word_dict, key=word_dict.get)
print(max_word, word_dict[max_word])
```
使用readlines方法:
```
word_dict = {}
with open('words.txt', 'r') as f:
lines = f.readlines()
for line in lines:
words = line.split()
for word in words:
if word in word_dict:
word_dict[word] += 1
else:
word_dict[word] = 1
print(word_dict)
max_word = max(word_dict, key=word_dict.get)
print(max_word, word_dict[max_word])
```
这两段代码的核心思路都是一样的,先读取文件中每一行的内容,然后使用split()方法将其分割成单个单词,再遍历每一个单词,统计其出现的频次,最后打印出字典和出现频次最高的单词及其频次。区别只是一个使用readline方法,一个使用readlines方法。
阅读全文