gensim.corpora中Dictionaryd的用法

from gensim.corpora import Dictionary
dictionary = Dictionary(corpus)
这里的corpus需要时二维列表形式,如
corpus = [['我', '在', '玉龙雪山', '我', '我', '我', '我'], ['我', '喜欢', '玉龙雪山'], ['我', '还要', '去', '玉龙雪山']

得到的dictionary事宜个包含很多信息的集合,若要对其中信息进行查看可如下操作:
输出dictionary

print(str(dictionary))
>>>"Dictionary(75 unique tokens: ['\\n', '23', '、', '厂', '台积']...)"

查看 字典,{单词id,在多少文档中出现}

print(dictionary.dfs)    #字典,{单词id,在多少文档中出现}
>>>{1: 3, 0: 1, 2: 3, 3: 1, 5: 1, 4: 1}

查看 字典,{单词id,在所有文档中共出现几次}

print(dictionary.cfs)
>>>{1: 7, 0: 1, 2: 3, 3: 1, 5: 1, 4: 1}

查看 文档数目:

dictionary.num_docs     #文档数目
>>> 3

查看 dictionary 中 {词的id:词}

print (dict(dictionary. items()))
或者 
print(dictionary.id2token)
>>> {0: '在', 1: '我', 2: '玉龙雪山', 3: '喜欢', 4: '去', 5: '还要'}

查看 {词:词的id}

print(dictionary.token2id)
>>> {'在': 0, '我': 1, '玉龙雪山': 2, '喜欢': 3, '去': 4, '还要': 5}

查看共有多少个词,多少个不重复的词

print(dictionary.num_pos) #查看所有词的个数

print(dictionary.num_nnz) #查看所有词的个数

添加新的语句:

newlist=jieba.lcut('美国以应对芯片危机,美国出现投票信任危机')
result, missing = dictionary.doc2bow(newlist, allow_update=True, return_missing=True) # allow_update : 更新当前字典;return_missing : 返回字典中不存在的词,result为b文章转换得到的词袋,列表[(单词id,词频)]
result
>>> [(6, 1), (7, 1), (8, 1), (9, 1), (10, 1), (11, 1), (12, 2), (13, 1), (14, 1)]  #词袋 [(单词id,单词出现频率)]
missing
>>>[] #不在字典中的词及其词频,字典[(单词,词频)]
print(dict(dictionary.items()))  #查看加入后的{词:词id}
>>>{0: '在', 1: '我', 2: '玉龙雪山', 3: '喜欢', 4: '去', 5: '还要', 6: '以', 7: '信任危机', 8: '出现', 9: '危机', 10: '应对', 11: '投票', 12: '美国', 13: '芯片', 14: ','}

for id, freq in result:
    print(id, dictionary.id2token[id], freq) #查看bow的内容
>>>
61
7 信任危机 1
8 出现 1
9 危机 1
10 应对 1
11 投票 1
12 美国 2
13 芯片 1
141

过滤词频

过滤文档频率大于 no_below,小于 no_above*num_docs的词
dictionary.filter_extremes(no_below=2,no_above=0.5,keep_n=10)
print(dictionary.dfs) #查看结果

原文链接:https://blog.csdn.net/weixin_45747396/article/details/121512711

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值