当前位置:   article > 正文

对列表中的词进行词频排序

对列表中的词进行词频排序
  1. from collections import Counter
  2. import jieba
  3. sentence = "当眼泪流出眼眶的一瞬间,一切都成了定局。只有把眼泪流回到血液中," \
  4. "才有力挽狂澜的希望,你若想力挽狂澜就必须放弃流泪的自由," \
  5. "就像蒲公英要想飞的更高更远,就必须忍住背井离乡的愁苦。"
  6. sentence_words = jieba.lcut(sentence)
  7. word_counts = Counter(sentence_words)
  8. # 出现频率最高的3个单词
  9. top_three = word_counts.most_common(3) # 不加参数,对所有词频进行排序
  10. print(top_three)
  11. # Outputs [('的', 5), (',', 5), ('就', 3)]

 查询某个词出现词频

  1. print(word_counts['的'])
  2. # output 5

添加词汇的两种方法:

其一:

  1. add_words = ['孤独', '的', '蒲公英']
  2. for word in add_words:
  3. word_counts[word] += 1
  4. print(word_counts['的'])
  5. # output 6

其二:

  1. word_counts.update(add_words)
  2. print(word_counts['的'])
  3. # output 7

还可以进行简单的数学运算操作:

  1. add_counts = Counter(add_words)
  2. out_counts = word_counts + add_counts
  3. print(out_counts)
  4. # output Counter({'的': 8, ',': 5, '蒲公英': 4, '就': 3, '孤独': 3, '眼泪': 2, '。': 2, '力挽狂澜': 2, '必须': 2, '更': 2, '当': 1, '流出': 1, '眼眶': 1, '一瞬间': 1, '一切': 1, '都': 1, '成': 1, '了': 1, '定局': 1, '只有': 1, '把': 1, '流': 1, '回到': 1, '血液': 1, '中': 1, '才': 1, '有': 1, '希望': 1, '你': 1, '若想': 1, '放弃': 1, '流泪': 1, '自由': 1, '像': 1, '要': 1, '想': 1, '飞': 1, '高': 1, '远': 1, '忍住': 1, '背井离乡': 1, '愁苦': 1})
  5. #*******************************
  6. add_counts_1 = out_counts - word_counts
  7. print(add_counts_1)
  8. # output Counter({'的': 1, '蒲公英': 1, '孤独': 1})

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/109688
推荐阅读