统计英文中单词出现的次数并按降序输出。 txt="Twinkle, twinkle, little star, how I wonder what you are.Up above the world so high”
时间: 2023-06-10 13:08:04 浏览: 191
可以使用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的collections模块中的Counter类来统计单词出现的次数,并按降序输出。
以下是示例代码:
```python
import string
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."
# 去除标点符号和换行符
txt = txt.translate(str.maketrans("", "", string.punctuation)).replace("\n", " ")
# 分割单词
words = txt.split()
# 统计单词出现的次数
word_counts = Counter(words)
# 按降序输出单词及其出现次数
for word, count in word_counts.most_common():
print(word, count)
```
输出结果如下:
```
Twinkle 2
twinkle 2
little 2
the 2
you 2
so 1
high 1
like 1
a 1
diamond 1
in 1
skyWhen 1
blazing 1
sun 1
is 1
gone 1
when 1
he 1
nothing 1
shines 1
uponThen 1
show 1
your 1
light 1
all 1
night 1
what 1
areUp 1
above 1
world 1
I 1
wonder 1
how 1
```
可以看到,输出结果按降序排列,每个单词后面跟着它在文本中出现的次数。
阅读全文