赞
踩
- from collections import Counter
- import jieba
-
- sentence = "当眼泪流出眼眶的一瞬间,一切都成了定局。只有把眼泪流回到血液中," \
- "才有力挽狂澜的希望,你若想力挽狂澜就必须放弃流泪的自由," \
- "就像蒲公英要想飞的更高更远,就必须忍住背井离乡的愁苦。"
- sentence_words = jieba.lcut(sentence)
- word_counts = Counter(sentence_words)
- # 出现频率最高的3个单词
- top_three = word_counts.most_common(3) # 不加参数,对所有词频进行排序
- print(top_three)
- # Outputs [('的', 5), (',', 5), ('就', 3)]
查询某个词出现词频
- print(word_counts['的'])
- # output 5
添加词汇的两种方法:
其一:
- add_words = ['孤独', '的', '蒲公英']
- for word in add_words:
- word_counts[word] += 1
- print(word_counts['的'])
- # output 6
其二:
- word_counts.update(add_words)
- print(word_counts['的'])
- # output 7
还可以进行简单的数学运算操作:
- add_counts = Counter(add_words)
- out_counts = word_counts + add_counts
- print(out_counts)
- # 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})
-
- #*******************************
- add_counts_1 = out_counts - word_counts
- print(add_counts_1)
- # output Counter({'的': 1, '蒲公英': 1, '孤独': 1})
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。