简体   繁体   English

如何在读取 Python 中的文件行时不创建无限循环?

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

I've looked around, but can't figure out why my 3rd function, info_count(), is running on an infinite loop:我环顾四周,但无法弄清楚为什么我的第三个 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()

The first two return the proper results and ends.前两个返回正确的结果并结束。 But my count keeps looping and I don't see why it doesn't break at the end of the run.但是我的计数一直在循环,我不明白为什么它在运行结束时没有中断。

In addition, once I get that count, I want to later print those lines out, but only a specific section ie the IP address, which may vary on each line that returns "[info]".此外,一旦我得到了这个计数,我想稍后打印这些行,但只打印一个特定的部分,即 IP 地址,它可能因返回“[info]”的每一行而异。 Please advise.请指教。

Do you mean why the program prints count many time?你的意思是为什么程序打印多次? If so, you should remove an indent:如果是这样,您应该删除一个缩进:

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

For the IP addresses (requested in the comments):对于 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()

Square brackets are special characters, so we want to tell python that we only want them as part of the string, To do that, right before the special character, we put a backslash.方括号是特殊字符,所以我们想告诉 python 我们只希望它们作为字符串的一部分,为此,在特殊字符之前,我们放一个反斜杠。

The * is to tell python we want all the characters between [client and ] . *是告诉 python 我们想要[client]之间的所有字符。

The . . dot tells the program that we accept any character besides newlines. dot 告诉程序我们接受除换行符之外的任何字符。

The ? ? is to tell python not to be greedy . 就是告诉 python 不要贪心

For example, say this is our string: 'Hello, my name is Ann. What is your name?' 例如,假设这是我们的字符串: 'Hello, my name is Ann. What is your name?' 'Hello, my name is Ann. What is your name?'

We want to find all the characters between 'm' and 'n' . 我们想找到'm''n'之间的所有字符。

If our program is greedy, it will give us ['y name is Ann. What is your ']如果我们的程序是贪婪的,它会给我们['y name is Ann. What is your '] ['y name is Ann. What is your '] , if not greedy, ['y ', 'e is A'] . ['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