建立字典

代码:

# 分类
# 社会 国际 体育 科技 。。。
# 建立一个字典(词库)以备特征的提取

import json 
from bs4 import BeautifulSoup
import jieba
import jieba.posseg as pseg

# 读取json文件
input_file = "new_items.json"
f = open(input_file, 'rb')

# 词性过滤
POS_include = ['n', 'nz', 'ns', 'nr', 'nt', 'v', 'vn', 'a', 'i', 'j', 'l', 's']
# 停用词
EXCEPT = [',','。','的', '也','!']



twords = []
for text in f:
    # 将json转换为字典形式
    dic = json.loads(text)
    content = dic["content"]

    # soup解析
    soup = BeautifulSoup(content, "lxml")
    new_content = "\n".join([x.text for x in soup.findAll('p')])

    # 词性标注
    words = pseg.cut(new_content)
    for word in words:
        w, pos = word.word, word.flag # 词, 词性
        if pos in POS_include and w not in EXCEPT and len(w) > 1:
            twords.append(w)

运行结果:

Building prefix dict from the default dictionary ...
Dumping model to file cache /var/folders/yb/chzkd3w944sgt4h17gz3vy600000gn/T/jieba.cache
Loading model cost 1.408 seconds.
Prefix dict has been built succesfully.

代码:

print("===" * 20)
print(len(twords))

# 用set去重后词的个数
print("===" * 20)
print(len(set(twords)))

# 查看前100个词
print("===" * 20)
print(" ".join(list(set(twords)))[:100])

运行结果:

============================================================
3434796
============================================================
123484
============================================================
淑萍 猜猜 接轨 数学老师 廓然 固沙 抬举 大英 审查室 清澈 加拿大 同学 联为 打听一下 共同努力 职院 王跃文 半遮半掩 坚定 密集 需求方 通化市 酒仙 卸车 申花 称道 自民党 柳姓 索罗

代码:

# 过滤 
# 如何用词的频数筛选字典
from collections import defaultdict
frequency = defaultdict(int)

# 如果出现这个词出现在twords,则加1
for text in twords:
    frequency[text] += 1
print(type(frequency))

# 去除了频数小于1的, 保留频数大于1的词
new_words = [w for w in twords if frequency[w] > 1]
print("===" * 20)
print(new_words[:40])
with open("prepare_corpus.txt", "w") as f:
    f.write("\n".join(new_words))
    
print("===" * 20)
print(len(new_words))
print("===" * 20)
print(type(new_words[0]))
print("===" * 20)
print(new_words[0])

运行结果:

<class 'collections.defaultdict'>
============================================================
['标题', '年度', '国家', '最高', '科学技术', '奖得主', '中国工程院', '院士', '侯云德', '病毒', '鏖战', '侯云德', '江苏', '著名', '医学', '病毒学家', '中国工程院', '院士', '中国', '疾病', '预防', '控制中心', '病毒', '预防', '控制', '研究员', '艾滋病', '病毒性', '肝炎', '重大', '传染病', '防治', '科技', '重大', '专项', '总体', '技术', '总师', '生物医学', '领域']
============================================================
3392306
============================================================
<class 'str'>
============================================================
标题

代码:

# 按照词频从大到小排序 value
freq_sorted = sorted(frequency.items(), key=lambda x:x[1], reverse=True)
# 查看前20
for k, v in freq_sorted[:20]:
    print("%s %d"%(k, v) )

运行结果:

中国 26866
美国 14697
没有 12836
表示 12311
比赛 11631
进行 10765
问题 10189
报道 10065
国家 8816
时间 8490
工作 8388
记者 8329
可能 7968
发展 7610
公司 7156
责任编辑 7090
认为 6371
球员 6274
情况 6183
开始 6180
In [32]:

代码:

# 建立字典
import gensim
dictionary = gensim.corpora.Dictionary([new_words])
# 查看前10个
print("===" * 20)
print("/".join(list(dictionary.token2id.keys())[:10]))
print("===" * 20)
print(dictionary.token2id["4s店"])
print("===" * 20)
print(dictionary[2])
# 保存字典
dictionary.save("corpus.dict")

运行结果:

============================================================
1号店/4S店/4s店/AT&T/A型/A座/A股/A轮/B型/B超
============================================================
2
============================================================
4s店
In [ ]:


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值