2013-01-31 63 views
0
def get_word_count(wordlist, final): 
    regex = [] 
    count = [[] for x in xrange(len(wordlist))] 
    frequency = [] 
    regex = makeregex(wordlist) 
    for i in range(len(final)-1): 
     size = os.stat(final[i]).st_size 
     fil = open(final[i]) 
     if(fil): 
      print final[i] + " read!" 
      data = mmap.mmap(fil.fileno(), size, access=mmap.ACCESS_READ) 
      for j in range (len(wordlist)): 
       count[j].append(re.findall(regex[j], data)) 
     fil.close() 
    for k in range(len(wordlist)): 
     frequency.append(sum(count[k])) 
    print frequency 

count是一個列表列表,每個列表都有一些數字存儲在列表中。我想每一個列表的總和存儲爲元素的新列表frequencypython中不支持的操作數類型錯誤

當我運行代碼我得到一個錯誤:

Traceback (most recent call last): 
File "C:\Users\Animesh\Desktop\_zipf.py", line 52, in <module> 
get_word_count(wordlist, final) 
File "C:\Users\Animesh\Desktop\_zipf.py", line 32, in get_word_count 
frequency.append(sum(count[k])) 
TypeError: unsupported operand type(s) for +: 'int' and 'list' 

我應該在我的代碼改變? 請幫助

+1

錯誤來自上面的代碼或內部'makeregex'?如果'final [i]'不是一個字符串,但它看起來並沒有達到那麼遠,代碼也可能在'print final [i] +「read!中失敗。 –

+1

可以在調用sum之前輸出'count [k]'的值嗎?你的'count [k]'有這樣的'[[],2]',試着總結一下,它會給你那個錯誤信息。 –

回答

2
count[j].append(re.findall(regex[j], data)) 

你通過正則表達式加入找到的詞列表排列count[j],所以每個count元素是字符串列表清單,從而調用sum(count[k])時的錯誤。

我想你要附加到count[k]發現單詞的數量:

count[j].append(len(re.findall(regex[j], data))) 
1

如果你想更簡單,你可以擺脫count = [[] for x in xrange(len(wordlist))]的,只是有count = []後來在for循環你讓它增加一個臨時變量並在for循環之後追加它。

size = 0 
for j in range (len(wordlist)): 
    size += len(re.findall(regex[j], data)) #thanks to CharlesB for this bit 
count.append(size) #you could also cut out the middle man and just append frequency 
相關問題