从键盘输入一个英文句子或单词组成的字符串,可以不包含标点符号,但单词之间要有空格分开,因为列表统计句子中每个单词的出现频次,以列表形式输出字符串以及每个单词对应频次。提示:字符串的split方法可以将字符串转成列表。输入样例:I am chinese student and I am studying in Henan university of technology 。Python程序
时间: 2023-06-14 10:08:30 浏览: 270
可以这样实现:
```python
s = input("请输入英文句子或单词组成的字符串:")
words = s.split() # 将字符串转换成列表,以空格为分隔符
freq = {} # 用字典来统计单词出现的频次
for word in words:
freq[word] = freq.get(word, 0) + 1 # 如果字典中不存在该单词,则值为0,否则加1
result = [(word, freq[word]) for word in freq] # 将字典转换成列表,元素为元组,元组第一个元素为单词,第二个元素为频次
result.sort(key=lambda x: x[1], reverse=True) # 按照频次从大到小排序
print("单词\t\t频次")
for word, count in result:
print(f"{word}\t\t{count}")
```
输入样例:
```
请输入英文句子或单词组成的字符串:I am chinese student and I am studying in Henan university of technology
```
输出结果:
```
单词 频次
I 2
am 2
student 1
chinese 1
and 1
studying 1
in 1
Henan 1
university 1
of 1
technology 1
```
阅读全文