2017-05-07 93 views
0

我想計算一個正在進行的數據集上的正則表達式搜索的輸出,但由於某種原因,我的計數被大量關閉。我想知道我做錯了什麼,我怎麼能得到一個正式的計數。我應該有大約1500場比賽,但我不斷收到一個錯誤,說「'int'對象不可迭代」。正則表達式輸出計數

import re 

with open ('Question 1 Logfile.txt' , 'r') as h: 
    results = [] 
    count = [] 
    for line in h.readlines(): 
     m = re.search(r'(((May|Apr)(\s*)\w+\s\w{2}:\w{2}:\w{2}))', line) 
     t = re.search(r'(((invalid)(\s(user)\s\w+)))',line) 
     i = re.search(r'(((from)(\s\w+.\w+.\w+.\w+)))', line) 
     if m and t and i: 
      count += 1 
      print(m.group(1),' - ',i.group(4),' , ',t.group(4)) 
      print(count) 
+0

這裏計數是在初始化過程中的列表,你不能增加一個列表object.Make計數= 0 – bigbounty

+0

@bigbounty是的,謝謝我不相信我錯過了。最後一個簡單的問題是,這種方法會計算每個輸出的數量,最後如何計算總數? – user7823345

+0

@bigbounty我如何評論評論?你可以通過說count.append(1)來解釋你的意思嗎? – user7823345

回答

0

您想增加滿足一系列循環迭代條件的次數。這裏的困惑似乎是如何做到這一點,以及增加什麼變量。

下面是一個小例子,它捕捉您遇到的困難,如OP和OP註釋中所述。這是一個學習的例子,但它也提供了一些解決方案的選項。

count = [] 
count_int = 0 

for _ in range(2): 
    try: 
     count += 1 
    except TypeError as e: 
     print("Here's the problem with trying to increment a list with an integer") 
     print(str(e)) 

    print("We can, however, increment a list with additional lists:") 
    count += [1] 
    print("Count list: {}\n".format(count)) 

    print("Most common solution: increment int count by 1 per loop iteration:") 
    count_int +=1 
    print("count_int: {}\n\n".format(count_int)) 

print("It's also possible to check the length of a list you incremented by one element per loop iteration:") 
print(len(count)) 

輸出:

""" 
Here's the problem with trying to increment a list with an integer: 
'int' object is not iterable 

We can, however, increment a list with additional lists: 
Count list: [1] 

Most common is to increment an integer count by 1, for each loop iteration: 
count_int: 1 


Here's the problem with trying to increment a list with an integer: 
'int' object is not iterable 

We can, however, increment a list with additional lists: 
Count list: [1, 1] 

Most common is to increment an integer count by 1, for each loop iteration: 
count_int: 2 


It's also possible to check the length of a list you incremented 
by one element per loop iteration: 
2 
""" 

希望有所幫助。祝你好運學習Python!