2017-02-21 12 views
1

私は、ログファイルを解析し、IPアドレスのトップヒットといくつかの他のものを返すプログラムに取り組んでいます。現在、私は問題を抱えており、私はこの問題の答えを私が今行っていることに解釈できません。これは私のすべてのコードです:今、私は問題を抱えていますunhashableタイプ:リスト

import gzip 
from collections import Counter 
logFileName = open('C:\\Users\\Pawlaczykm\\Desktop\\fileNames.txt', 'r') 
ipAdd = [] 
landingPages = [] 
ALL_ipAdd = [] 
ALL_landingPages = [] 
# everything after this line gets done to all files 
for line in logFileName.readlines(): 
# rstrip removes a blank line from output 
# print 'Summary of: ' + line.rstrip() 

# use gzip to decompress the file 
with gzip.open('C:\\Users\\Pawlaczykm\\Desktop\\logFiles\\' + line.rstrip() + '.gz', 'rb') as f: 
    # we extract the ip addresses in lines 15-18 
    for eachLine in f: 
     parts = eachLine.split('\t') 
     if len(parts) > 1: 
      ipAdd.append(parts[2]) 
ALL_ipAdd.append(ipAdd) 
# use gzip to decompress the file 
with gzip.open('C:\\Users\\Pawlaczykm\\Desktop\\logFiles\\' + line.rstrip() + '.gz', 'rb') as f: 
    # we extract the landing pages 
    for eachLine in f: 
     parts = eachLine.split('\t') 
     if len(parts) > 1: 
      variable = parts[8].split('?')[0] 
      landingPages.append(variable) 
v): (-v, k))[:10] 
ALL_landingPages.append(landingPages) 

ALL_ipAddDict = dict(Counter(ALL_ipAdd).most_common()) 
sortedALL_ipAdd = sorted(ALL_ipAddDict.iteritems(), key=lambda (k, v): (-v,  k))[:10] 
print 'Top IPs of all files' 
print(sortedALL_ipAdd) 
ALL_LandingPageDict = dict(Counter(ALL_landingPages).most_common()) 
sortedALL_LandingPage = sorted(ALL_LandingPageDict.iteritems(), key=lambda  (k, v): (-v, k))[:10] 
print 'Top landing pages of all files' 
print (sortedALL_LandingPage) 

は次の行にあります。

ALL_ipAddDict = dict(Counter(ALL_ipAdd).most_common()) 

出力Iは、プログラム全体がこれです実行すると:

Traceback (most recent call last): 
    File "C:/Users/Pawlaczykm/PycharmProjects/LogParse/parseText.py", line 35, in <module> 
    ALL_ipAddDict = dict(Counter(ALL_ipAdd).most_common()) 
    File "C:\Python27\lib\collections.py", line 477, in __init__ 
self.update(*args, **kwds) 
    File "C:\Python27\lib\collections.py", line 567, in update 
self[elem] = self_get(elem, 0) + 1 
TypeError: unhashable type: 'list' 

誰かが私を助けることができますか?これはイライラしています。

+2

リストは変更可能なので、ハッシュ可能ではありません。その結果、それらを辞書のキーとして使用することはできません –

+0

'ALL_ipAdd'の中身を表示できますか? – Bahrom

+0

@ Ev.Kounisリストを取って辞書に入れて辞書をハッシュする方法はありますか? – mattp341

答えて

-2

これは正常です。 ALL_ipAddはリストのリストです。 Counterは、リスト、我々はALL_ipAddはリストのリストであると結論付けることができますあなたのコードALL_ipAdd = []ipAdd = []ALL_ipAdd.append(ipAdd)から文字列または任意の他のハッシュ可能タイプ:)

+0

*リストはハッシュ可能ではありません。 –

3

を必要とします。 Counterは、サブタイプがdictで、カウントする前にアイテムをハッシュします。リストは変更可能であるため(リストが変更された場合はハッシュが変更されるため)、ハッシュすることはできません。リストはCounterオブジェクトではカウントできません。あなたがそれらを数える前に、タプルに内側のリストを変換することができ、この解決するために

ALL_ipAddDict = dict(Counter(map(tuple, ALL_ipAdd)).most_common()) 
関連する問題