2013-08-29 150 views
0

我不知道如何攻擊這個問題!!!比較字符串和計算出現

我有3列出了用一個字,一個標籤,它出現在文檔的數量:

v1 = [['be', 'VSIS3S0', 1], ['scott', 'NP00000', 2], ['north', 'NCMS000', 1], ['revolution', 'NP00000', 1], ['name', 'VMP00SM', 1]] 
v2 = [['mechanic', 'NCMS000', 1], ['be', 'VSIS3S0', 1], ['tool', 'AQ0CS0', 1], ['sam', 'NP00000', 1], ['frida', 'NP00000', 1]] 
v3 = [['be', 'VSIP3S0', 1], ['scott', 'NP00000', 1], ['who', 'NP00000', 1]] 

如何建立一個函數,接收這些列表比較每個字,這樣,例如,字bev1出現在三個列表中,在這種情況下附加到結果列表(1 * log(3/3)),其中1->出現的最大值(它是子列表的第三個元素),日誌分子3 - >常量,日誌分母3 - >因爲這個詞出現在v1v2v3

接下來我們scott - >在這種情況下附加到所述結果列表(2 * log(3/2)),2 - 發生之>最大word's值,登錄分子3 - >恆定,登錄分母2 - >因爲單詞「斯科特」出現v1v2

接下來我們north - >在這種情況下,追加到結果列表(1 * log(3/1)),1 - 發生之>最大word's值,登錄分子3 - >不變,分母數1 - >因爲這個詞「北」出現只有v1

下一步,我們有revolution - >在這種情況下追加到結果列表(1 * log(3/1)),1 - >出現的最大字的值,日誌分子3 - >常量,日誌分母1 - >,因爲出現'北'字只有v1

下一步我們有name - >在這種情況下追加到結果列表(1 * log(3/1)),1 - >出現的最大字的值,日誌分子3 - >常量,日誌分母1 - >,因爲單詞'name'出現只有v1

而且我們通過mechanicbetool等比較其他詞做同樣與v2,計算次數的最大值和multuplying它w/ log(3/?)如果詞出現或不v1v3依賴。

這是我v1嘗試:

def f1(v1, v2, v3): 
    res =[] 
    for e in v1: 
     if e != 0: 
      if e in v2 and e in v3: 
       res.append(0) 
      elif e in v2: 
       res.append(e * math.log(3/2)) 
      else: 
       res.append(e * math.log(3)) 
    return res 

返回:[0, 2.1972245773362196, 0, 0, 0, 0]

,這顯然是不結果

它sholud返回類似:

[['be', 0.47], ['scott', 0.35 ], ['north', 0.47], ['revolution', 0.47], ['north', 0.47]] 

希望你可以幫我解決這個問題,我有一週試圖解決它!

謝謝

回答

0

根據你的描述,我

import math 
v1 = [['be', 'VSIS3S0', 1], ['scott', 'NP00000', 2], ['north', 'NCMS000', 1], ['revolution', 'NP00000', 1], ['name', 'VMP00SM', 1]] 
v2 = [['mechanic', 'NCMS000', 1], ['be', 'VSIS3S0', 1], ['tool', 'AQ0CS0', 1], ['sam', 'NP00000', 1], ['frida', 'NP00000', 1]] 
v3 = [['be', 'VSIP3S0', 1], ['scott', 'NP00000', 1], ['who', 'NP00000', 1]] 

v = [v1,v2,v3] 

countdict = {} 
for vi in v: 
    for e in vi: 
     countdict[e[0]] = countdict.get(e[0],0) + 1 

scoredict = {} 
for vi in v: 
    for e in vi: 
     scoredict[e[0]] = scoredict.get(e[0],0) + (e[2] * math.log10(3.0/countdict[e[0]])) 

print scoredict 

我輸出保存爲一個字典,那就是:

{'be': 0.0, 'revolution': 0.47712125471966244, 'north': 0.47712125471966244, 'name': 0.47712125471966244, 'sam': 0.47712125471966244, 'tool': 0.47712125471966244, 'who': 0.47712125471966244, 'scott': 0.5282737771670437, 'mechanic': 0.47712125471966244, 'frida': 0.47712125471966244} 
+0

感謝大衛這是相當多的結果! !一個評論:python數學日誌(3)拋出1.098,但一個普通的計算器顯示0.47 ...爲什麼? – JPP

+0

什麼是您需要的日誌基礎? – badc0re

+0

我需要log10()。 – JPP