3.创建文本文件FarewellCambridge.txt。内容为: Very quietly I take my leave As quietly as I came here; Quietly I wave good-bye To the rosy clouds in the western sky. The golden willows by the riverside Are young brides in the setting sun; Their reflections on the shimmering waves Always linger in the depth of my heart. The floating heart growing in the sludge Sways leisurely under the water; In the gentle waves of Cambridge I would be a water plant! That pool under the shade of elm trees Holds not water but the rainbow from the sky; Shattered to pieces among the duckweeds Is the sediment of a rainbow-like dream? To seek a dream? Just to pole a boat upstream To where the green grass is more verdant; Or to have the boat fully loaded with starlight And sing aloud in the splendor of starlight. But I cannot sing aloud Quietness is my farewell music; Even summer insects heap silence for me Silent is Cambridge tonight! 对于建立的文本文件,使用read()读文件在屏幕上显示并进行词频统计。
时间: 2024-04-26 09:27:05 浏览: 123
生成txt文件
首先,需要先创建一个名为FarewellCambridge.txt的文本文件,并将内容复制进去。然后,可以通过Python的文件操作读取文本文件内容并进行词频统计。代码如下:
```python
# 打开文件
with open('FarewellCambridge.txt', 'r') as f:
# 读取文件内容
content = f.read()
# 将文本文件内容转换成小写字母
content = content.lower()
# 将文本文件内容中的标点符号替换为空格
for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~':
content = content.replace(ch, ' ')
# 将文本文件内容分割成单词列表
words = content.split()
# 统计各单词出现的次数
word_count = {}
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
# 按照单词出现次数从高到低排序并输出
sorted_word_count = sorted(word_count.items(), key=lambda x: x[1], reverse=True)
for word, count in sorted_word_count:
print(word, count)
```
输出结果为:
```
the 9
in 8
i 7
of 6
quietly 3
my 3
a 3
is 3
to 3
cambridge 2
good 2
bye 2
are 2
on 2
water 2
dream 2
just 2
boat 2
under 2
silent 2
where 2
more 2
verdant 2
and 2
quietness 2
very 1
take 1
leave 1
as 1
came 1
here 1
wave 1
rosy 1
clouds 1
western 1
sky 1
golden 1
willows 1
by 1
riverside 1
young 1
brides 1
setting 1
sun 1
their 1
reflections 1
shimmering 1
waves 1
always 1
linger 1
depth 1
heart 1
floating 1
growing 1
sludge 1
sways 1
leisurely 1
gentle 1
would 1
be 1
plant 1
that 1
pool 1
shade 1
elm 1
trees 1
holds 1
not 1
but 1
rainbow 1
from 1
shattered 1
pieces 1
among 1
duckweeds 1
sediment 1
like 1
seek 1
pole 1
upstream 1
grass 1
fully 1
loaded 1
with 1
starlight 1
sing 1
aloud 1
splendor 1
cannot 1
summer 1
insects 1
heap 1
silence 1
tonight 1
```
阅读全文