Python获得一篇文档的不重复词列表并创建词向量
生活随笔
收集整理的這篇文章主要介紹了
Python获得一篇文档的不重复词列表并创建词向量
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?獲得一篇文檔的不重復詞列表:
def loadDataSet():postingList = [['my', 'dog', 'has', 'flea', 'problems', 'help', 'please'],['maybe', 'not', 'take', 'him', 'to', 'dog', 'park', 'stupid'],['my', 'dalmation', 'is', 'so', 'cute', 'I', 'love', 'him'],['stop', 'posting', 'stupid', 'worthless', 'garbage'],['mr', 'licks', 'ate', 'my', 'steak', 'how', 'to', 'stop', 'him'],['quit', 'buying', 'worthless', 'dog', 'food', 'stupid']]return postingListdef createVocabList(dataSet):vocabSet = set([]) # 創建空集合for document in dataSet:vocabSet = vocabSet | set(document) # 取并集return list(vocabSet)word = loadDataSet() word_set = createVocabList(word) print(word_set)輸出:(可以看到輸出沒有重復詞匯)
['stop', 'not', 'stupid', 'how', 'food', 'him', 'posting', 'worthless', 'I', 'has', 'please', 'dalmation', 'licks', 'problems', 'help', 'garbage', 'buying', 'maybe', 'my', 'to', 'quit', 'flea', 'so', 'mr', 'dog', 'park', 'is', 'love', 'steak', 'ate', 'take', 'cute']
接下來是由輸入文檔和詞匯表來創建詞向量的函數:
vocabList是詞匯表,inputSet是輸入文檔,輸出是文檔向量,向量每一個元素是1或0,分別表示詞匯表的單詞在輸入文檔中是否出現
def setOfWords2Vec(vocabList, inputSet):returnVec = [0]*len(vocabList) # 創建一個和詞匯表等長的全0向量for word in inputSet:if word in vocabList:returnVec[vocabList.index(word)] = 1else: print("the word: %s is not in my Vocabulary!" % word)return returnVec?
總結
以上是生活随笔為你收集整理的Python获得一篇文档的不重复词列表并创建词向量的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: windows10下安装pytorch并
- 下一篇: python assert 与 sl