2016-12-06 13 views
0

Pythonを使用してテキストをCSVファイルのベクトルに変換したいと考えています。Pythonを使用してテキストをCSVファイルのベクトルに変換し、ユークリッド距離を見つける方法

def text_to_vector私のコードではエラーが発生しています。

import re,math 
from collections import Counter 

WORD = re.compile(r'\w+') 

    def euclidean_distance(vec1,vec2): 
     intersection = set(vec1.keys()) & set(vec2.keys()) 
     return sqrt(sum(pow(vec1[x]-vec2[x],2) for x in intersection) 

    def text_to_vector(text): 
     words = WORD.findall(text) 
     return Counter(words) 

#text1 = 'This is a foo bar sentence .' 
#text2 = 'This sentence is similar to a foo bar sentence .' 
text1 = file('Stacks1.csv').read() 
text2= file('reftopics.csv').read() 
vector1 = text_to_vector(text1) 
vector2 = text_to_vector(text2) 

euclidean = euclidean_distance(vector1, vector2)*100 

print 'Euclidean:', euclidean 
+2

エラー/エラーメッセージは何ですか? 'euclidean_distance()'にリストの理解を誤っているのに加えて、間違ったインデントには私には間違いがありません。 – infotoni91

答えて

0

euclidean_distance(vec1, vec2)のようなものでなければなりません:

def euclidean_distance(vec1, vec2): 
    intersection = set(vec1.keys()) & set(vec2.keys()) 
    return math.sqrt(sum([pow(vec1[s]-vec2[s], 2) for s in intersection])) 

リスト内包のご使用は間違っています。

関連する問題