在电脑任意文件夹中新建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()和readlines()两种方法编写代码实现以下功能: 读取words.txt中的内容,创建字典统计文本内容中出现的词语及其对应的频次,打印该字典; 找到该文本文件中出现频次最高的词语,打印该词语和它出现的频次。 需要注意的是出现频次最高的可能不止一个单词,比如本题中to和be都出现了8次,因此程序运行结果为:
时间: 2024-02-28 10:57:44 浏览: 41
使用readline()方法实现:
```python
word_dict = {}
with open('words.txt', 'r') as f:
line = f.readline()
while line:
words = line.strip().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_freq_word = []
max_freq = 0
for word, freq in word_dict.items():
if freq > max_freq:
max_freq_word = [word]
max_freq = freq
elif freq == max_freq:
max_freq_word.append(word)
print("出现频次最高的词语是%s,出现了%d次。" % (", ".join(max_freq_word), max_freq))
```
使用readlines()方法实现:
```python
word_dict = {}
with open('words.txt', 'r') as f:
lines = f.readlines()
for line in lines:
words = line.strip().split()
for word in words:
if word in word_dict:
word_dict[word] += 1
else:
word_dict[word] = 1
print(word_dict)
max_freq_word = []
max_freq = 0
for word, freq in word_dict.items():
if freq > max_freq:
max_freq_word = [word]
max_freq = freq
elif freq == max_freq:
max_freq_word.append(word)
print("出现频次最高的词语是%s,出现了%d次。" % (", ".join(max_freq_word), max_freq))
```
这两段代码的实现思路是一样的,都是先将文件中的内容读取到内存中,然后对每个单词进行计数并保存到字典中,最后找到出现频次最高的词语。使用readline()方法时,需要使用while循环来读取每一行;使用readlines()方法时,可以直接将文件的所有行读取到一个列表中,然后用for循环遍历每一行。
阅读全文