【单词次数统计】 输入一段英文(不区分大小写),对这段英文中每个单词出现的次数进行统计,输出出现次数排名前五的单词和次数。 输入输出样例如下: 输入: From hill to hill no bird in flight;From path to path no man in sight.A lonely fisherman afloat,Is fishing snow in lonely boat. 输出: [('in', 3), ('from', 2), ('hill', 2), ('to', 2), ('no', 2)]
时间: 2024-01-10 21:02:43 浏览: 206
好的,这是一个比较典型的编程问题。我们可以使用 Python 中的字符串操作和字典来实现。下面是一个示例代码:
import re
from collections import Counter
def count_words(text):
# 使用正则表达式匹配所有单词
words = re.findall(r'\b\w+\b', text.lower())
# 使用 Counter 统计单词出现次数
word_counts = Counter(words)
# 返回出现次数排名前五的单词和次数
return word_counts.most_common(5)
text = input("请输入英文字符串:")
top_five_words = count_words(text)
print(f"出现次数排名前五的单词和次数为:{top_five_words}")
运行程序后,输入英文字符串,即可输出出现次数排名前五的单词和次数。程序中使用了正则表达式 \b\w+\b
来匹配所有单词,它的含义和上一个问题中的一样。使用 Counter 类可以方便地统计单词出现次数,并使用 most_common 方法获取出现次数排名前五的单词和次数。注意,由于题目中要求不区分大小写,所以程序中使用了 lower 方法将所有单词转换为小写字母。
相关问题
输入一段英文(不区分大小写),对这段英文中每个单词出现的次数进行统计,输出出现次数排名前五的单词和次数
好的,你可以参考下面的代码实现:
text = input("请输入一段英文:").lower() # 获取输入的文本并转换为小写
# 定义一个字典来存储每个单词出现的次数
word_count = {}
# 将文本按照空格分割成单词列表
words = text.split()
# 遍历单词列表,统计每个单词出现的次数
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
# 对字典按照值排序,并取出前五个
top_words = sorted(word_count.items(), key=lambda x: x[1], reverse=True)[:5]
# 输出出现次数排名前五的单词和次数
print("出现次数排名前五的单词和次数为:")
for word, count in top_words:
print(f"{word}: {count}")
这段代码与上一个问题的代码大致相同,不同之处在于我们首先将输入的文本转换为小写,然后只统计单词出现的次数,不考虑其他字符。接着,使用sorted
函数对字典按照值进行排序,并取出前五个,存储在top_words
变量中。最后,遍历top_words
变量,输出出现次数排名前五的单词和次数。
用Python语言写代码,输入一段英文 (不区分大小写)对这段英文中每个单词出现的次数进行统计,输出出现次数排名前五的单词和次数
好的,以下是Python代码实现:
# 输入一段英文
text = input("请输入一段英文:")
# 将英文转换为小写
text = text.lower()
# 将标点符号替换为空格
for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~':
text = text.replace(ch, ' ')
# 分割单词
words = text.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)
# 输出出现次数排名前五的单词和次数
print("出现次数排名前五的单词和次数为:")
for i in range(5):
print("{0}: {1}".format(sorted_word_count[i][0], sorted_word_count[i][1]))
你可以将这段代码复制到Python解释器中运行,输入一段英文,即可得到出现次数排名前五的单词和次数(不区分大小写)。
相关推荐















