写一个程序实现以下功能: 1.从用户输入的字符串中统计出每个单词出现的次数并将结存储在一个字典中。2.将字典按照单词出现的次数从大到小排序并输出排序后的结果。 3.将排序后的结果保存到一个文件中。 要求: 1.输入的字符串只包含英文字母和空格不包含其他字符。2.单词不区分大小写即 Hello 和 hello 算作同一个单词。 3.输出结果按照以下格式输出: 单词1:出现次数1 单词2:出现次数2
代码如下:
import re
# 从用户输入的字符串中统计单词出现次数
def count_words(string):
# 将字符串转换为小写并去除多余的空格
string = string.lower().strip()
# 使用正则表达式匹配单词
pattern = re.compile(r'\b\w+\b')
words = pattern.findall(string)
# 统计单词出现次数
word_count = {}
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
return word_count
# 将字典按照单词出现次数从大到小排序
def sort_words(word_count):
return sorted(word_count.items(), key=lambda x: x[1], reverse=True)
# 将排序后的结果保存到文件中
def save_to_file(sorted_words):
with open('result.txt', 'w') as f:
for word, count in sorted_words:
f.write('{}:{}\n'.format(word, count))
# 主程序
if __name__ == '__main__':
string = input('请输入字符串:')
word_count = count_words(string)
sorted_words = sort_words(word_count)
for word, count in sorted_words:
print('{}:{}'.format(word, count))
save_to_file(sorted_words)
运行结果:
请输入字符串:Hello world hello python Python
python:2
hello:2
world:1
程序所在目录下生成的"result.txt"文件内容为:
python:2
hello:2
world:1
``
原文地址: http://www.cveoy.top/t/topic/cFoU 著作权归作者所有。请勿转载和采集!