1

count以下の for ループでは、ループが最初に実行されたときにのみ正しい値が返される理由を理解しようとしています。

テキスト ファイル内の特定の文字列を検索してカウントする解析プログラムを作成しています。ただ、一ヶ所で困っています。

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

助けてくれてありがとう。これを正しく機能させることができないようです。

4

1 に答える 1

5

ファイルは最後まで渡されるため、このメソッドは初回のみ機能します。メソッドを再度呼び出すと、それ以上の行はありません。for ループの前に filex.seek(0) を呼び出して、ファイルの位置をリセットします。

于 2012-06-26T15:11:54.237 に答える