我是Python的新手,最近不得不做一些文本处理来做两个文本之间的余弦相似性。
目前,我已经能够对文本进行基本的预处理,例如小写,标记文本,删除停止词,并使用NLTK库对这些单词进行词干处理。现在,我能够从我得到的所有文本文件中创建一个独特的单词列表。
现在,在我创建的唯一单词列表中,我只想根据我所拥有的文本文件将其向量化为1(其余的单词为0)。
因此,例如,在将唯一的单词列表向量化之后,它应该如下所示:
awesome| best | carry | elephant | fly | home | irresponsible | implicit
1 | 1 | 0 | 0 | 0 | 1 | 0 | 0我在这里尝试过搜索和查看堆栈溢出,但似乎常见的解决方案之一是在转换列表时使用scikit学习特性提取。不过,我只想要0或者1.并且1应该由文本文件指定。
例如,有一个文本文件(在将其全部矢量化为1之后),我想要计算与此字典的相似性.所以它应该如下所示:
Text_to_Compare.txt
awesome | fly | implicit
1 | 1 | 1然后,将"Text_to_Compare.txt“与唯一单词列表进行比较,并计算相似度结果。
有谁能好心地指导我如何将唯一单词的列表向量化为0或1,并将"Text_to_Compare.txt“向量化到所有1?
谢谢!
发布于 2015-01-22 15:32:05
这就是你想做的吗?
text_file = ['hello','world','testing']
term_dict = {'some':0, 'word':0, 'world':0}
for word in text_file:
if word in term_dict:
term_dict[word] = 1如果您已经标记了您的文件(Python中的.split()方法),那么它们将在列表中可用。假设你已经标准化了每一个术语(降低,词干,去掉标点符号等等)在您的字典和text_file中,上述代码应该可以工作。只需将dict中的所有值设置为0,并循环文件,检查单词是否为in dict。如果是,那么将该值设置为1。
下面是如何生成值设置为0的字典:
new_dict = {word:0 for word in text_file}这是一个词典理解。请再次注意,我的代码假设您正在规范所有术语--将苹果与苹果进行比较--这是处理文本时的关键。
最后编辑。如果您有两个唯一术语列表(在标记化和规范化之后)
def normalize(term):
#do stuff -- i.e., lower; stem; strip punctuation; etc.
pass
word_list_one = [normalize(word) for word in text_doc.split()]
word_list_two = [normalize(word) for word in other_text_doc.split()]
# if you know the longest of your lists, then you can create a dictionary of ones and zeros from the two lists.
word_dict = dict([(word,1) if word in word_list_one else (word,0) for word in word_list_two])
# that's it. in the above code, word_list_two should be the longer of your two lists (assuming I understand your code properly)
# Note: someone with more python experience could definitely improve my code. I just wanted show you another option.如果这对你有用,请告诉我。希望它能帮上忙!
https://stackoverflow.com/questions/28092505
复制相似问题