Python词频统计代码
时间: 2024-05-27 20:06:31 浏览: 139
Python编写的词频统计工具
5星 · 资源好评率100%
当前提供两种Python词频统计代码,一种是列表方法,另一种是字典方法。
1. 列表方法代码:
```python
import jieba
txt = input("请输入文本:")
words = jieba.lcut(txt)
uniquewords = list()
counts = list()
for word in words:
if len(word) == 1:
continue
else:
if word in uniquewords:
tempindex = uniquewords.index(word)
counts[tempindex] += 1
else:
uniquewords.append(word)
counts.append(1)
for i in range(len(counts)):
print("{0:<10}{1:>5}".format(uniquewords[i],counts[i]))
```
[引用1]
2. 字典方法代码:
```python
import jieba
txt = input("请输入文本:")
words = jieba.lcut(txt)
counts = {}
for word in words:
if len(word) == 1:
continue
else:
counts[word] = counts.get(word,0) + 1
items = list(counts.items())
items.sort(key = lambda x:x, reverse = True)
for i in range(len(items)):
word, count = items[i]
print("{0:<10}{1:>5}".format(word,count))
```
[引用2]
阅读全文