请用python编写在需要统计若干段文字(英文)中的单词数量,并且还需统计每个单词出现的次数。 注1:单词之间以空格(1个或多个空格)为间隔。 注2:忽略空行或者空格行。 要求: 统计前,需要从文字中删除指定标点符号!.,:*?#和0至9的数字。 注意:所谓的删除,就是用1个空格替换掉相应字符。 统计单词时需要忽略单词的大小写。 单词个数为0时。只需显示“0”。 输入格式: 若干行英文,最后以%%%为结束。。 输出格式: 单词数量 出现次数排名前6的单词(次数按照降序排序,如果次数相同,则按照键值的字母升序排序)及出现次数。 输入样例: 在这里给出一组输入。例如: Failure is probably The fortification in your pole! It#is like a1 peek your wallet as the thief when You are thinking how2 to. spend several hard-won lepta. when yoU are? wondering whether new money it#has laid background Because of: yOu5?, then at the6 heart of the Tom say: Who is the best? No one dare to say yes. most lax alert and! most low awareness and* left it %%% godsend failed it is !!!!! 输出样例: 在这里给出相应的输出。例如: 52 the=5 is=3 it=3 you=3 and=2 are=2
时间: 2024-02-28 08:55:57 浏览: 29
以下是Python代码实现:
```python
import re
from collections import Counter
# 定义要删除的标点符号和数字
punctuation = '.,:*?#0123456789'
pattern = re.compile('[{}]'.format(punctuation))
# 读取输入
s = ''
while True:
line = input().strip()
if line == '%%%':
break
if not line:
continue
s += line.lower() + '\n'
# 删除标点符号和数字
s = pattern.sub(' ', s)
# 统计单词数量和出现次数
words = s.split()
word_count = Counter(words)
# 输出结果
if len(word_count) == 0:
print('0')
else:
print(len(word_count), end=' ')
for word, count in word_count.most_common(6):
print(word, end='=')
print(count, end=' ')
```
使用说明:
1. 运行代码后,按照题目要求输入英文文本,以%%%为结尾。
2. 程序会自动统计单词数量和出现次数,并输出结果。
3. 注意:程序中会忽略空行或者空格行,并忽略单词的大小写。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)