代码未检测到文件中的正确数量

时间:2014-11-05 03:00:45

标签: file python-3.x io

通常我的代码工作正常,只有一小部分。在下面给出的文件中,程序应该输出红色或硬肉的安全动物的数量。它应该是8但我得到5.我将如何解决这个问题?相关摘录如下。谢谢。

文本文件:

#color     size     flesh     class
brown     large    hard      safe
green     large    hard      safe
red       large    soft      dangerous
green     large    soft      safe


red       small    hard      safe
red       small    hard      safe
brown     small    hard      safe
green     small    soft      dangerous
green     small    hard      dangerous
red       large    hard      safe
brown     large    soft      safe
green     small    soft      dangerous
red       small    soft      safe
red       large    hard      dangerous
red       small    hard      safe
green     small    hard      dangerous

代码:

for line in infile:
    if line[0] != '#':
        data = line.strip().split()

        if data:
           animals = animals + 1

            if data[3] == 'dangerous':
                dangerous = dangerous + 1
            elif data[3] == 'safe' and data[1] == 'large':
                large_safe = large_safe + 1
            elif data[0] == 'brown' and data[3] == 'dangerous':
                brown_dangerous = brown_dangerous + 1                        
            elif (data[3] == 'safe') and (data[0] == 'red' or data[2] == 'hard'):
                safe_red_hard = safe_red_hard + 1



    print("Total animals: "+ animals + "\n")
    print("Dangerous: "+ dangerous + "\n")
    print("Brown and dangerous: "+ brown_dangerous + "\n")
    print("Large and safe: "+ large_safe + "\n")
    print("Safe and red color or hard flesh: "+ safe_red_hard + "\n")

1 个答案:

答案 0 :(得分:1)

主要问题在于elif语句:

elif data[3] == 'safe' and data[1] == 'large':
    large_safe = large_safe + 1
elif data[0] == 'brown' and data[3] == 'dangerous':
    brown_dangerous = brown_dangerous + 1                        
elif (data[3] == 'safe') and (data[0] == 'red' or data[2] == 'hard'):

有了这个逻辑,任何大而安全的动物都永远不会被视为安全,红色或硬。解决方案是使用if语句:

animals = 0
large_safe = 0
dangerous = 0
brown_dangerous = 0
safe_red_hard = 0
with open('file') as infile:
    for line in infile:
        if line[0] == '#':
            continue
        data = line.strip().split()
        if data:
            animals = animals + 1
            if data[3] == 'dangerous':
                dangerous = dangerous + 1
            if data[3] == 'safe' and data[1] == 'large':
                large_safe = large_safe + 1
            if data[0] == 'brown' and data[3] == 'dangerous':
                brown_dangerous = brown_dangerous + 1________________________
            if (data[3] == 'safe') and (data[0] == 'red' or data[2] == 'hard'):
                safe_red_hard = safe_red_hard + 1

print("Total animals: "+ str(animals) +"\n")
print("Dangerous: "+ str(dangerous) +"\n")
print("Brown and dangerous: "+ str(brown_dangerous) + "\n")
print("Large and safe: "+ str(large_safe) + "\n")
print("Safe and red color or hard flesh: "+ str(safe_red_hard) + "\n")