在需要统计若干段文字(英文)中的单词数量,并且还需统计每个单词出现的次数。 注1:单词之间以空格(1个或多个空格)为间隔。 注2:忽略空行或者空格行。 要求: 统计前,需要从文字中删除指定标点符号!.,:*?#和0至9的数字。 注意:所谓的删除,就是用1个空格替换掉相应字符。 统计单词时需要忽略单词的大小写。 单词个数为0时。只需显示“0”。 输入格式: 若干行英文,最后以%%%为结束。。 输出格式: 单词数量 出现次数排名前6的单词(次数按照降序排序,如果次数相同,则按照键值的字母升序排序)及出现次数。
时间: 2024-02-15 13:04:03 浏览: 21
好的,我可以帮你解决这个问题。以下是我给出的解决方案:
```python
import re
from collections import Counter
# 删除指定标点符号和数字
def remove_punctuation(text):
return re.sub('[^a-zA-Z\s]', ' ', text)
# 统计单词数量并排序
def count_words(text):
words = text.lower().split()
count = Counter(words)
return count.most_common()
# 读入文本
text = ''
while True:
line = input()
if line == '%%%':
break
text += line + '\n'
# 删除标点符号和数字
text = remove_punctuation(text)
# 统计单词数量
count = count_words(text)
# 输出结果
print(len(count))
for word, word_count in count[:6]:
print('{} {}'.format(word, word_count))
```
这个程序会先读入文本,然后删除指定标点符号和数字,并统计单词数量。最后输出单词数量和出现次数排名前6的单词及其出现次数。
注意,这个程序中的 `remove_punctuation` 函数使用了正则表达式来删除标点符号和数字。`count_words` 函数使用了 Python 内置的 `collections.Counter` 类来统计单词数量,并使用 `most_common` 方法来排序。