[英]Count the number of rows that each word appears in
我有一個訓練數據集,它是一個 numpy 數組,形狀為 (4800,1)。 它有一列字符串,每一行對應來自不同電子郵件的文本。
我想創建一個字典來計算每個單詞出現在使用 python 中的電子郵件數(或行數)。 最終只選擇出現在至少 10 封電子郵件中的詞。 我只能弄清楚如何計算整個數據集中出現的單詞的頻率,而不是在多少行/電子郵件中。 以下代碼是我到目前為止
下面是一個數組是什么樣子的例子,它應該輸出什么。
[['red blue green green']
['red blue blue']
['red red red']]
輸出:
{'red': 3, 'blue': '2', 'green': '1'}
def vocab_dict(file):
d = dict()
for row in xTrain:
words = row.split(" ")
for word in words:
if word in d:
d[word] = d[word] + 1
else:
d[word] = 1
d = dict((k, v) for k, v in d.items() if v >= 10)
return d
我被困在如何修改上面的代碼,該代碼計算一個單詞在整個數據集中出現的次數到每行(每封電子郵件)中一個單詞出現的次數。
假設我們有一個字符串列表l
。 然后我們可以這樣做:
from collections import Counter
word_lists = [text.split(" ") for text in l] # split into words
word_sets = [set(word_list) for word_list in word_lists] # make sets, discard duplicates
c = Counter()
for word_set in word_sets:
c.update(word_set)
print(c)
c
現在將為每個單詞包含該單詞所在的電子郵件數量。
您想遍歷每一行,並為該句子中的每個唯一單詞添加一個到表示該單詞的 dict 元素。 您可以通過將列表轉換為set
來獲取唯一詞。
def vocab_dict(data):
lines_count = {}
for line in data:
for word in set(line.split()):
old_count = lines_count.get(word, 0)
lines_count[word] = old_count + 1
return lines_count
dict.get()
函數返回該鍵的值,如果該鍵不存在,則默認為 0。 或者,您可以使用collections.defaultdict
。
測試:
l = ['red blue green green', 'red blue blue', 'red red red']
vocab_dict(l)
# Out: {'green': 1, 'blue': 2, 'red': 3}
一種選擇是將words
列表更改為一組,以消除重復。 你可以這樣做:
[...]
for word in set(words):
if word in d:
[...]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.