簡體   English   中英

如何在讀取 Python 中的文件行時不創建無限循環?

[英]How do I not create an infinite loop while reading file lines in Python?

我環顧四周,但無法弄清楚為什么我的第三個 function info_count() 在無限循環中運行:

def error_statement():
    errorLog = open("error_log.txt", "r")
    for line in errorLog:
        if "[error]" in line:
            print(line)

def statistics_statement():
    errorLog = open("error_log.txt", "r")
    for line in errorLog:
        if "statistics" in line:
            print(line)

def info_count():
    errorLog = open("error_log.txt", "r")
    count = 0
    for line in errorLog:
        if "[info]" in line:
            count += 1
        print(count)

error_statement()
statistics_statement()
info_count()

前兩個返回正確的結果並結束。 但是我的計數一直在循環,我不明白為什么它在運行結束時沒有中斷。

此外,一旦我得到了這個計數,我想稍后打印這些行,但只打印一個特定的部分,即 IP 地址,它可能因返回“[info]”的每一行而異。 請指教。

你的意思是為什么程序打印多次? 如果是這樣,您應該刪除一個縮進:

def info_count():
    errorLog = open("error_log.txt", "r")
    count = 0
    for line in errorLog:
        if "[info]" in line:
            count += 1
    print(count)

對於 IP 地址(在評論中要求):

import re

def ip():
    error_log = open('error_log.txt','r')
    ip = re.findall('\[client .*?\]', error_log.read())
    print('\n'.join([x[8:-1] for x in ip]))
ip()

方括號是特殊字符,所以我們想告訴 python 我們只希望它們作為字符串的一部分,為此,在特殊字符之前,我們放一個反斜杠。

*是告訴 python 我們想要[client]之間的所有字符。

. dot 告訴程序我們接受除換行符之外的任何字符。

? 就是告訴 python 不要貪心

例如,假設這是我們的字符串: 'Hello, my name is Ann. What is your name?' 'Hello, my name is Ann. What is your name?'

我們想找到'm''n'之間的所有字符。

如果我們的程序是貪婪的,它會給我們['y name is Ann. What is your '] ['y name is Ann. What is your '] ,如果不是貪婪的話, ['y ', 'e is A']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM