简体   繁体   English

读取文件中未知数量的行

[英]Reading an unknown number of lines in a file

I wrote the code below, but it specifies the number of lines in the file.我写了下面的代码,但它指定了文件中的行数。 I'm wondering how I can change it so that it will read an unknown number of lines?我想知道如何更改它以使其读取未知数量的行?

n = int(input("instance: "))
tp, tn, fp, fn = 0
for i in range(n):
    real, predicted = map(int, input().split(' '))
    for num in i:
        if real == 1 and predicted == 1:
            tp += 1
        elif real == 0 and predicted == 0:
            tn += 1
        elif real == 1 and predicted == 0:
            fn += 1
        else:
            fp += 1

pr = tp / (tp + fp)
rc = tp / (tp + fn)
f1 = 2 * ((pr * rc) / (pr + rc))
print("f1= ", f1)

My code reads these lines and compares numbers on each line with each other, but not with numbers on the other lines.我的代码读取这些行并将每行上的数字相互比较,但不与其他行上的数字进行比较。

The input looks like this:输入如下所示:

1 1
0 0
0 1
0 1
1 0
0 1
0 0
1 1
0 0
0 0
0 0
0 0
1 1

Keep reading until EOFError is thrown:继续阅读直到抛出EOFError

tp, tn, fp, fn = 0
i = 0
try:
    while True:
        real, predicted = map(int, input().split(' '))
        for num in i:
            if real == 1 and predicted == 1:
                tp += 1
            elif real == 0 and predicted == 0:
                tn += 1
            elif real == 1 and predicted == 0:
                fn += 1
            else:
                fp += 1
        i += 1
except EOFError:
    pass
pr = tp / (tp + fp)
rc = tp / (tp + fn)
f1 = 2 * ((pr * rc) / (pr + rc))
print("f1= ", f1)

Your code has errors too:您的代码也有错误:

  • multiple variables can't be assigned to the same value using unpacking.不能使用解包将多个变量分配给相同的值。
  • range needs to be used if you want to count up to a number.如果要计算一个数字,则需要使用range

This should fix them:这应该解决它们:

tp = tn = fp = fn = 0
i = 0
try:
    while True:
        real, predicted = map(int, input().split(' '))
        for num in range(i):
            if real == 1 and predicted == 1:
                tp += 1
            elif real == 0 and predicted == 0:
                tn += 1
            elif real == 1 and predicted == 0:
                fn += 1
            else:
                fp += 1
        i += 1
except EOFError:
    pass
pr = tp / (tp + fp)
rc = tp / (tp + fn)
f1 = 2 * ((pr * rc) / (pr + rc))
print("f1= ", f1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM