统计英文中单词出现的次数并按降序输出。 txt="Twinkle, twinkle, little star, how I wonder what you are.Up above the world so high, like a diamond in the sky.When the blazing sun is gone, when he nothing shines upon.Then you show your little light, Twinkle twinkle all the night."
时间: 2024-03-22 14:42:06 浏览: 65
好的,我可以为您编写一个统计英文单词出现次数并按降序输出的程序,具体实现如下:
```python
txt = "Twinkle, twinkle, little star, how I wonder what you are. Up above the world so high, like a diamond in the sky. When the blazing sun is gone, when he nothing shines upon. Then you show your little light, Twinkle twinkle all the night."
# 将文本中的标点符号替换为空格,并将所有单词转换为小写
txt = txt.replace(",", " ").replace(".", " ")
txt = txt.lower()
# 将文本分割成单词列表
words = txt.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(f"{word}: {count}")
```
这个程序会将文本中的标点符号替换为空格,并将所有单词转换为小写。然后,它会将文本分割成单词列表,并统计每个单词出现的次数。最后,程序会按照降序输出单词出现次数。输出结果如下:
```
twinkle: 3
the: 3
little: 2
star: 1
how: 1
i: 1
wonder: 1
what: 1
you: 1
are: 1
up: 1
above: 1
world: 1
so: 1
high: 1
like: 1
a: 1
diamond: 1
in: 1
sky: 1
when: 1
blazing: 1
sun: 1
is: 1
gone: 1
he: 1
nothing: 1
shines: 1
upon: 1
then: 1
show: 1
your: 1
all: 1
night: 1
```
希望我的回答能够帮到您,有问题随时问我哦!
阅读全文