从列表中计算出现次数 Python

时间:2021-03-23 07:18:55

标签: python list count

我必须编写一个程序,从文件中读取数据,将数据附加到列表中,读取列表并输出以下错误出现的次数“password < 6”和“password > 10”

我无法编写代码让程序读取这些特定单词的字符串并输出它们出现的次数。

def main():

    PASSWORD_LOG_FILE = "ITWorks_password_log.txt"

    list_data = []

    input_file = open(PASSWORD_LOG_FILE, "r")

    for line in input_file:
        list_data.append(line)

    input_file.close()

    for error in list_data:
        print(error, end="")

    for error in range(0, len(list_data)):
        count_pw_too_small = list_data.count("password < 6")
        count_pw_too_large = list_data.count("password > 10")

    print("\nThe number of passwords that were under the minimum length: ", count_pw_too_small)
    print("The number of passwords that were over the maximum length: ", count_pw_too_large)

main()

下面是它应该读取的列表中的数据:

2019-07-22 16:24:42.843103,密码<6

1 个答案:

答案 0 :(得分:0)

与我的讲师交谈后,我们得出了以下解决方案,该解决方案没有使用计数方法,但仍然运行良好。

def main():

    PASSWORD_LOG_FILE = "ITWorks_password_log.txt"

    list_data = []

    input_file = open(PASSWORD_LOG_FILE, "r")

    for line in input_file:
        list_data.append(str(line))

    input_file.close()

    count_pw_too_small = 0
    count_pw_too_large = 0

    for error in list_data:
        print(error, end="")
        if "< 6" in error:
            count_pw_too_small += 1
        elif "> 10" in error:
            count_pw_too_large += 1


    print("\nThe number of passwords that were under the minimum length: ", count_pw_too_small)
    print("The number of passwords that were over the maximum length: ", count_pw_too_large)

main()
相关问题