2012-06-26 2 views
1

아래 for 루프에서 count의 올바른 값은 루프가 처음 실행될 때만 반환된다는 것을 이해하려고합니다.루프에 대해 처음으로 count에 대한 올바른 값이 반환되는 이유는 무엇입니까?

저는 텍스트 파일에서 특정 문자열을 찾아 계산하는 구문 분석 프로그램을 만들고 있습니다. 그러나, 나는 한 곳에서 약간의 문제를 겪고있다.

def callbrowse(): 
    filename = tkFileDialog.askopenfilename(filetypes = (("Text files", "*.txt"),("HTML files", ".html;*.htm"),("All files", "*.*"))) 
    print filename 
    try: 
     global filex 
     global writefile 
     filex = open(filename, 'r') 
     print "Success!!" 
     print filename 
    except: 
     print "Failed to open file" 

######This returns the correct count only the first time it is run. The next time it ######returns 0. If the browse button is clicked again, then this function returns the ######correct count again. 
def count_errors(error_name): 
    count = 0 
    for line in filex: 
     if error_name == "CPU > 79%": 
      stringparse = "Utilization is above" 
     elif error_name == "Stuck touchscreen": 
      stringparse = "Stuck touchscreen" 
     if re.match("(.*)" + "Utilization is above" + "(.*)",line): 
      count = count + 1 
    return count 

도움 주셔서 감사합니다. 나는 이것이 올바르게 작동하는 것처럼 보일 수 없다.

+0

흠 ... 코드를 읽기가 매우 어렵습니다. 좀 더 읽기 쉽게 줄 바꿈과 들여 쓰기를 추가하십시오. – carmenism

+1

실제로 count_errors를 호출하는 코드에서 포인트가 보이지 않습니다 ... – mnowotka

답변

5

이 메서드는 파일이 끝까지지나 가기 때문에 처음으로 작동합니다. 메서드를 다시 호출하면 더 이상 선이 없습니다. for 루프 앞에 filex.seek (0)을 호출하여 파일 위치를 재설정했습니다.

관련 문제