使用python查找列表中文档的术语频率
l=['cat sat besides dog']
我试图找到语料库中每个单词的词频。
术语freq =(文档中出现单词的次数/文档中单词的总数)。
我尝试对一个文档执行此操作,但是当列表中有多个文档时,我会收到错误消息。
def tf(corpus):
dic={}
for document in corpus:
for word in document.split():
if word in dic:
dic[word]+=1
else:
dic[word]=1
for word,freq in dic.items():
print(word,freq)
dic[word]=freq/len(document.split())
return dic
tf(d)
我想传递此列表,并希望在每个文档中找到单词的tf。但是我得到错误的tf值。 l = ['猫坐在狗旁边','狗坐在床上']
答案 0 :(得分:0)
有些第三方程序包可以满足您的需求。但是要使用代码,问题是您要向频率加1。因此,在第一次尝试之后,您将在第一个文档中使用其频率更新word
的值。但是,下次您添加1时,不是频率而是计数。这就是为什么在打印单词和频率时使用sat 1.25
的原因。
您需要做的就是移动最后一个for循环。
sum(map(len, (document.split() for document in corpus)))
将获得整个语料库中的单词总数。
def tf(corpus):
dic={}
for document in corpus:
for word in document.split():
if word in dic:
dic[word] = dic[word] + 1
else:
dic[word]=1
for word,freq in dic.items():
print(word,freq)
dic[word]=freq/sum(map(len, (document.split() for document in corpus)))
return dic
tf(d)
输出:
{'cat': 0.1111111111111111,
'sat': 0.2222222222222222,
'besides': 0.1111111111111111,
'dog': 0.2222222222222222,
'the': 0.1111111111111111,
'on': 0.1111111111111111,
'bed': 0.1111111111111111}
每个文档的频率?只需移动dic
,即可为每个文档创建一个。
def tf(corpus):
tfs = []
for document in corpus:
dic={}
for word in document.split():
if word in dic:
dic[word]+=1
else:
dic[word]=1
for word,freq in dic.items():
print(word,freq)
dic[word]=freq/len(document.split())
tfs.append(dic)
return tfs
输出:
[{'cat': 0.25, 'sat': 0.25, 'besides': 0.25, 'dog': 0.25},
{'the': 0.2, 'dog': 0.2, 'sat': 0.2, 'on': 0.2, 'bed': 0.2}]