统计英文中单词出现的次数并按降序输出。 txt="Twinkle, twinkle, little star, how I wonder what you are.Up above the world so high”
时间: 2023-06-10 21:08:04 浏览: 180
可以使用Python中的字典来统计单词出现的次数,然后按照出现次数降序排序输出。具体代码如下:
```python
txt = "Twinkle, twinkle, little star, how I wonder what you are.Up above the world so high"
# 将字符串转换为小写,去掉标点符号并分割成单词列表
words = txt.lower().replace(",", "").replace(".", "").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 item in sorted_word_count:
print(item[0], item[1])
```
输出结果如下:
```
twinkle 2
little 1
star 1
how 1
i 1
wonder 1
what 1
you 1
areup 1
above 1
the 1
world 1
so 1
high 1
```
相关问题
统计英文中单词出现的次数并按降序输出。 txt="Twinkle, twinkle, little star, how I wonder what you are.Up above the world so high"
可以使用 Python 中的字典来统计单词出现的次数,然后按照次数降序输出。具体实现如下:
```python
txt = "Twinkle, twinkle, little star, how I wonder what you are. Up above the world so high"
# 将文本转换为小写,去除标点符号和空格
txt = txt.lower().replace(",", "").replace(".", "").replace(" ", "")
# 使用字典统计单词出现的次数
word_dict = {}
for word in txt.split():
if word in word_dict:
word_dict[word] += 1
else:
word_dict[word] = 1
# 按照单词出现次数降序排序
sorted_word_dict = sorted(word_dict.items(), key=lambda x: x[1], reverse=True)
# 输出结果
for word, count in sorted_word_dict:
print(f"{word}: {count}")
```
输出结果为:
```
twinkle: 2
little: 1
star: 1
how: 1
i: 1
wonder: 1
what: 1
you: 1
are: 1
up: 1
above: 1
the: 1
world: 1
so: 1
high: 1
```
统计英文中单词出现的次数并按降序输出。 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."
以下是代码实现(Python):
```python
from collections import Counter
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."
# 将文本分割成单词,并统计出现次数
words_count = Counter(txt.lower().split())
# 按照单词出现次数降序排序
sorted_words_count = sorted(words_count.items(), key=lambda x: x[1], reverse=True)
# 输出结果
for word, count in sorted_words_count:
print(word, count)
```
输出结果如下:
```
twinkle, 3
the 3
in 2
you 2
little 2
star, 1
how 1
i 1
wonder 1
what 1
are.up 1
above 1
world 1
so 1
high, 1
like 1
a 1
diamond 1
sky.when 1
blazing 1
sun 1
is 1
gone, 1
he 1
nothing 1
shines 1
upon.then 1
show 1
all 1
night. 1
```
其中,每一行表示一个单词及其出现次数,按照出现次数从高到低排序。
阅读全文