[英]Python Bag of Words
[PYTHON 3.x]大家好,我正在從事自然語言處理項目,需要一些幫助。 我創建了一個包含所有文檔中不同單詞的詞匯表(列表)。 我想針對此詞匯表為每個文檔創建一個向量。 (Doc_POS_words包含100個文檔,其格式為Doc_POS_words [0] =第一個文檔,Doc_POS_words [1] =第二個文檔,依此類推。)
輸出:
# Doc_POS_words = [contains all the words of each document as below]
Doc_POS_words = [
['war','life','travel','live','night'],
['books','stuent','travel','study','yellow'],
]
# myVoc = [distinct words from all the documents as below]
myVoc = [
'war',
'life',
'travel',
'live',
'night',
'books',
'student',
'study',
'yellow'
]
# myVoc_vector = [ need this as well ]
# Doc_POS_words_BoW = [need this for each document]
PS:我沒有使用NLTK,因為我沒有使用NLTK支持的任何語言
謝謝。
檢查TfidfVectorizer
from sklearn.feature_extraction.text import TfidfVectorizer
corpus = ["Doc 1 words",
"Doc 2 words"]
vectorizer = TfidfVectorizer(min_df=1)
vectors = vectorizer.fit_transform(corpus)
我仍然不確定您要問什么,因此我將為您提供一些一般幫助。 我認為您需要使用python集。
https://docs.python.org/3/tutorial/datastructures.html#sets
以下是使用您問題中的數據的一些示例:
# create a set of the whole word list
myVocSet = set(myVoc)
for doc_words in Doc_POS_words:
# convert from list to set
doc_words = set(doc_words)
# want to find words in the doc also in the vocabulary list?
print(myVocSet.intersection(doc_words))
# want to find words in your doc not in the vocabulary list?
print(doc_words.difference(myVocSet))
# want to find words in the vocab list not used in your doc?
print(MyVocSet.difference(myVocSet))
這里有更多幫助:
>>> x = set(('a', 'b', 'c', 'd'))
>>> y = set(('c', 'd', 'e', 'f'))
>>>
>>> x.difference(y)
{'a', 'b'}
>>> y.difference(x)
{'f', 'e'}
>>> x.intersection(y)
{'c', 'd'}
>>> y.intersection(x)
{'c', 'd'}
>>> x.union(y)
{'a', 'b', 'd', 'f', 'e', 'c'}
>>> x.symmetric_difference(y)
{'a', 'b', 'f', 'e'}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.