获得一篇文档的不重复词列表:
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