Python编程,使用dict结构统计199801.txt中分词单元的频率, (1)输出频率最高的20个词(带着词性符号,标点等也算词)。 (2)输出频率最高的20个名词(词性符号为n,带着词性符号)。 (3)输出频率最高的20个成语(词性符号为i,带着词性符号)
时间: 2024-01-01 15:04:22 浏览: 29
好的,我知道了。这个问题需要涉及到Python的文件读取和dict结构的使用。以下是代码实现:
```python
import re
# 读取文件
with open('199801.txt', encoding='gbk') as f:
text = f.read()
# 去除换行符和空格
text = text.replace('\n', '').replace(' ', '')
# 使用正则表达式提取分词单元
pattern = r'\[(\w+)([^\[\]]*)\]'
tokens = re.findall(pattern, text)
# 统计频率
freq = {}
for token in tokens:
if token in freq:
freq[token] += 1
else:
freq[token] = 1
# 输出频率最高的20个词
top_words = sorted(freq.items(), key=lambda x: x[1], reverse=True)[:20]
print('频率最高的20个词:')
for word, count in top_words:
print(f'{word[0]}{word[1]}{word[2]}:{count}')
# 输出频率最高的20个名词
top_nouns = [(word, count) for word, count in freq.items() if word[1] == 'n'][:20]
print('频率最高的20个名词:')
for word, count in top_nouns:
print(f'{word[0]}{word[1]}{word[2]}:{count}')
# 输出频率最高的20个成语
top_idioms = [(word, count) for word, count in freq.items() if word[1] == 'i'][:20]
print('频率最高的20个成语:')
for word, count in top_idioms:
print(f'{word[0]}{word[1]}{word[2]}:{count}')
```
这个代码使用了正则表达式来提取分词单元,并使用了dict结构来统计频率。输出结果分别为频率最高的20个词、20个名词和20个成语,每个词后面跟着它在文本中出现的次数。
相关推荐
![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)