编写一个程序,首先反转输入的字符串,然后统计并输出字符串中的每个单词出现的次数python
时间: 2024-12-17 08:18:42 浏览: 27
编写一个Python程序,可以按照上述要求分为两部分:反转字符串和统计单词频率。以下是完整的代码:
```python def reverse_string(input_str): return input_str[::-1]
def word_count(sentence): # 将句子转换为小写并分割成单词列表 words = sentence.lower().split()
# 创建一个空字典来存储单词及其计数
word_dict = {}
# 遍历单词列表
for word in words:
# 如果单词已经在字典中,增加计数;否则添加到字典
if word in word_dict:
word_dict[word] += 1
else:
word_dict[word] = 1
return word_dict
获取用户输入
input_sentence = input("请输入一个字符串: ")
反转字符串
reversed_str = reverse_string(input_sentence)
统计单词频率
word_freq = word_count(reversed_str) print(f"反转后的字符串是: {reversed_str}") print("每个单词出现的次数:") for word, count in word_freq.items(): print(f"{word}: {count}")
相关推荐


















