[英]Why isn't there function to count Document Frequency (DF) in NLTK?
我正在尋找一個獲取特定術語DF的函數(意味着有多少文檔包含一個語料庫中的某個單詞),但是我似乎在這里找不到該函數。 該頁面僅具有獲取tf,idf和tf_idf值的功能。 我只在尋找DF。 我從文檔中復制了以下代碼,
matches = len([True for text in self._texts if term in text])
但我不喜歡它帶來的結果。 例如,如果我有一個字符串列表,並且我正在尋找單詞Pete
,那么它還包含我不想要的名稱Peter
。 例如。
texts = [['the', 'boy', 'peter'],['pete','the', 'boy'],['peter','rabbit']]
因此,我正在尋找顯示TWICE的pete
,但是上面顯示的代碼將告訴您有三個pete,因為它也算peter
。 我該如何解決? 謝謝。
至於您提出的問題(為什么(...)?):我不知道。
作為解決您的示例(請注意, peter
兩度出現的pete
只有一次:
texts = [['the', 'boy', 'peter'],['pete','the', 'boy'],['peter','rabbit']]
def flatten(l):
out = []
for item in l:
if isinstance(item, (list, tuple)):
out.extend(flatten(item))
else:
out.append(item)
return out
flat = flatten(texts)
len([c for c in flat if c in ['pete']])
len([c for c in flat if c in ['peter']])
比較兩個結果
編輯:
import collections
def counts(listr, word):
total = []
for i in range(len(texts)):
total.append(word in collections.Counter(listr[i]))
return(sum(total))
counts(texts,'peter')
#2
您的描述不正確。 當您在texts
搜索pete
時,您發布的表達式的確給出1,而不是3:
>>> texts = [['the', 'boy', 'peter'],['pete','the', 'boy'],['peter','rabbit']]
>>> len([True for text in texts if 'pete' in text])
1
匹配部分單詞的唯一方法是,如果您的文本沒有被標記化(即,如果texts
是一個字符串列表,而不是標記列表的列表)。
但是上面的代碼很糟糕,它根本沒有理由建立一個列表。 一種更好的(更常規的)點擊數計算方法是:
>>> sum(1 for text in texts if 'pete' in text))
1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.