# 精准模式 # 将句子最精准的切开,适合文本分析, # jieba.cut() 返回一个可迭代的数据类型(不存在冗余),此迭代器只能使用一次,类似于集合的迭代器 # jieba.lcut() 精准模式,返回一个列表类型
我这里使用精准模式来分词了,最大程度上使得没有冗余
# 封装成为一个函数
def wordStatistics(s:str):
'''
:param s: 需要分词的字符串
:return: 返回一个统计好分词的字典
'''
import jieba
dictionaryCount={} # 用于保存分词个数的字典
t=jieba.cut(s) # 接收一个可迭代对象
for s in t:
# 如果不存在,则第一次添加到字典
if not dictionaryCount.__contains__(s):
dictionaryCount[s]=1
# 存在,则使数量加1
else:
dictionaryCount[s]=dictionaryCount[s]+1
return dictionaryCount
测试
d=wordStatistics('我爱我的祖国和人民,祖国是我的故乡')
print(d)



