请编写py3程序,对一段英文文本,统计其中所有不同单词的个数,以及词频最大的前10%的单词。 所谓“单词”,是指由不超过80个单词字符组成的连续字符串,但长度超过15的单词将只截取保留前15个单词字符。而合法的“单词字符”为大小写字母、数字和下划线,其它字符均认为是单词分隔符。
时间: 2024-03-24 19:37:19 浏览: 13
好的,以下是一段实现你所需功能的 Python 3 代码,可以将其保存为一个.py文件并执行:
```python
import re
from collections import Counter
def get_words(text):
# 格式化文本,将所有非单词字符替换为空格
text = re.sub(r'\W+', ' ', text)
# 将文本中所有单词转换为小写
words = text.lower().split()
# 截取长度超过15的单词
words = [w[:15] if len(w) > 15 else w for w in words]
return words
def main():
with open('text.txt', 'r') as f:
text = f.read()
words = get_words(text)
word_count = Counter(words)
total_words = len(word_count)
top_words_count = int(total_words * 0.1)
top_words = word_count.most_common(top_words_count)
print(f'Total words: {total_words}')
print(f'Top {top_words_count} words:')
for word, count in top_words:
print(f'{word}: {count}')
if __name__ == '__main__':
main()
```
这段代码使用了正则表达式和Python标准库中的`Counter`类来完成你所需的功能。具体来说,它定义了一个`get_words`函数来将文本中的单词提取出来并进行格式化处理,然后使用`Counter`类来统计单词出现的频率,并找出出现频率最高的前10%的单词。最后,它输出了总单词数和词频最高的前10%单词。
请将代码中的`text.txt`替换为你要统计的文本文件名,并确保该文件与.py文件在同一目录中。