【问题标题】:One of methods doesn't work correctly when i call it当我调用它时,其中一种方法无法正常工作
【发布时间】:2022-11-15 10:46:52
【问题描述】:

我需要在日志文件中进行两次检查并显示结果。单独的方法可以正常工作,但是当我运行所有代码方法时hit_unique_check总是返回“PASS:所有命中都是独一无二的。”。对于三个中的两个。日志文件这个结果是不正确的。

import os


class ReadFiles:

    def __init__(self):
        self.current_file = ""
        self.shoot_from = "Shoot from"
        self.hit_player = "Hit player"

    def equally_check(self):
        shoot_from_list = []
        hit_player_list = []
        for line in self.current_file:
            if self.shoot_from in line:
                shoot_from_list.append(line)
            elif self.hit_player in line:
                hit_player_list.append(line)
        if len(shoot_from_list) == len(hit_player_list):
            print(" PASS: Shoots and hits are equal.\n")
        else:
            print(" FAIL: Shoots and hits are NOT equal.\n")

    def hit_unique_check(self):
        unique_hit_list = []
        duplicates = []
        for line in self.current_file:
            if self.hit_player in line:
                unique_hit_list.append(line)
            else:
                continue
        for i in unique_hit_list:
            if unique_hit_list.count(i) > 1:
                duplicates.append(i)
                print(i)
            else:
                continue
        if len(duplicates) < 1:
            print(" PASS: All hits are unique.\n")
        else:
            print(" FAIL: This hits are duplicated.\n")

    def run(self):
        for file in os.listdir():
            if file.endswith(".log"):
                print(f"Log file - {file}")
                self.current_file = open(f"{file}", 'rt')
                print(self.current_file.readlines, f"")
                self.equally_check()
                self.hit_unique_check()
                self.current_file.close()


if __name__ == "__main__":
    run = ReadFiles()
    run.run()

我运行我的 python 代码,但结果总是一样的:“PASS:所有命中都是唯一的。"。对于某些文件,它必须是 "FAIL:这个命中是重复的。“。我不确定方法中的问题hit_unique_check,并且不知道该怎么做。

你能解释一下,我如何才能使这种方法不仅单独正常工作吗?

【问题讨论】:

  • print(self.current_file.readlines, f"") 有什么意义?如果你想打印文件中的所有行,那么你需要调用函数.请注意,在你调用该函数后,你的文件句柄将被耗尽,你的循环将不再有效
  • 这也是您遇到错误的原因——一旦文件被迭代一次,您需要重新打开它,或者如果您想再次迭代它,则需要重新开始。如果您did any debugging,这将非常明显,尤其是如果您stepped through your code in a debugger
  • 也许您应该将该文件读入run 中的列表,然后在您的检查函数中重用该列表。或者,也许您的检查函数应该一次只执行一行,因此您只检查文件一次。

标签: python python-3.x


【解决方案1】:

考虑这个组织。每个函数都有一项任务,即评估并返回其结果。由调用者决定如何处理结果。另请注意,我使用的是计数器而不是列表,因为您并不真正关心列表包含的内容。还要注意 defaultdict 的使用,以避免重复搜索您的命中列表。

import os
from collections import defaultdict

class ReadFiles:

    def __init__(self):
        self.shoot_from = "Shoot from"
        self.hit_player = "Hit player"

    def equally_check(self, lines):
        shoot_from = 0
        hit_player = 0
        for line in lines:
            if self.shoot_from in line:
                shoot_from += 1
            elif self.hit_player in line:
                hit_player += 1
        return shoot_from == hit_player

    def hit_unique_check(self, lines):
        unique_hit_list = defaultdict(int)
        for line in lines:
            if self.hit_player in line:
                unique_hit_list[line] += 1
        duplicates = 0
        for k,v in unique_hit_list.items()
            if v > 1:
                duplicates += 1
                print(k)
        return not duplicates

    def run(self):
        for filename in os.listdir():
            if filename.endswith(".log"):
                print(f"Log file - {filename}")
                lines = open(filename, 'rt').readlines()
                print(lines)
                if self.equally_check(lines):
                    print(" PASS: Shoots and hits are equal.
")
                else:
                    print(" FAIL: Shoots and hits are NOT equal.
")
                if self.hit_unique_check(lines):
                    print(" PASS: All hits are unique.
")
                else:
                    print(" FAIL: This hits are duplicated.
")


if __name__ == "__main__":
    run = ReadFiles()
    run.run()

您甚至可以用计数器替换 hit_unique_check 中的循环:

from collections import Counter
...
    def hit_unique_check(self,lines):
        unique_hit_list = Counter(lines)
        for k,v in unique_hit_list,items():
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-28
    • 2015-11-04
    • 1970-01-01
    • 2016-03-12
    相关资源
    最近更新 更多