利用语料库五代•南唐二主词(poetrys.json),不调用库函数,分别统计n-gram(n=1、2)的词频,存储到相应的数据结构,该数据结构包括词(词本身)和词的频度(出现次数),将上述数据结构存储到文件,方便以后使用
时间: 2024-02-06 10:02:20 浏览: 40
以下为Python代码实现:
```python
import json
# 读取诗歌数据
with open('poetrys.json', 'r', encoding='utf-8') as f:
poetrys = json.load(f)
# 定义存储词频的数据结构
word_freq_1 = {}
word_freq_2 = {}
# 遍历每首诗歌
for poetry in poetrys:
# 遍历每个字
for i in range(len(poetry)):
word = poetry[i]
# 统计一元词频
if word in word_freq_1:
word_freq_1[word] += 1
else:
word_freq_1[word] = 1
# 统计二元词频
if i < len(poetry) - 1:
word_2 = poetry[i:i+2]
if word_2 in word_freq_2:
word_freq_2[word_2] += 1
else:
word_freq_2[word_2] = 1
# 将词频数据结构存储到文件
with open('word_freq_1.json', 'w', encoding='utf-8') as f:
json.dump(word_freq_1, f, ensure_ascii=False)
with open('word_freq_2.json', 'w', encoding='utf-8') as f:
json.dump(word_freq_2, f, ensure_ascii=False)
```
以上代码读取了诗歌数据,遍历每首诗歌,对于每个字统计一元词频,并且对于每两个相邻的字统计二元词频。最后将词频数据结构存储到文件中,以便以后使用。文件格式为JSON。