3.创建文本文件 FarewellCambridge-txt。内容为: Very quietly I take my leaveAs quietly as I came here;Quietly I wave good byeTo the rosy clouds in the western sky.The golden willows by the riversideAre young brides in the setting sun;Their reflections on the shimmering wavesAlways linger in the depth of my heart.The floating heart growing in the sludgeSways leisurely under the water;In the gentle waves of Cambridge[ would be a water plant!That pool under the shade of elm treesHolds not water but the rainbow from the sky;Shattered to pieces among the duckweedsIs the sediment of a rainbow like dream?To seek a dream? Just to pole a boat upstreamTo where the green grass is more verdant;Or to have the boat fully loaded with starlightAnd sing aloud in the splendor of starlight.But I cannot sing aloud Quietness is my farewell music; Even summer insects heap silence for meSilent is Cambridge tonight! 对于建立的文本文件,使用 read()读文件在屏幕上显示并进行词频统计。
时间: 2024-04-26 07:27:12 浏览: 121
生成txt文件
以下是读取文本文件并进行词频统计的代码:
```python
# 打开文本文件
with open('FarewellCambridge.txt', 'r') as f:
# 读取文件内容
text = f.read()
# 将文本按照空格和标点符号分割成单词列表
words = text.split()
# 统计每个单词的出现次数
word_counts = {}
for word in words:
if word in word_counts:
word_counts[word] += 1
else:
word_counts[word] = 1
# 输出词频统计结果
for word, count in word_counts.items():
print(f'{word}: {count}')
```
运行上述代码后,程序会打开名为 `FarewellCambridge.txt` 的文本文件,并读取其中的内容。然后,程序将文本按照空格和标点符号分割成单词列表,并统计每个单词的出现次数。最后,程序输出每个单词的词频统计结果。
注意,在将文本文件读取到内存中时,需要使用 `with` 语句来确保文件在使用完毕后被正确关闭。另外,在统计单词出现次数时,可以使用 Python 内置的字典数据结构来实现。
阅读全文