老麦克唐纳 动物总数应该是 44

Old MacDonald Sum of total animals should be 44

我的问题是我无法从我的 animals.txt 文件中获取动物的总数

2 pig oink
3 duck quack
4 horse neigh
5 lamb baa
6 chickens cluck
7 dog woof
8 cat meow
9 cow moo
----------
44

在我的 python 程序中显示总共 44 只动物。下面是我的。

def write_verse(vfile,animals): #function to write the animals into a verse.txt file
    with open('animals.txt', 'r') as f:
        result = sum(map(int, vfile))
    count = 1
    for animal in animals:  #loop to iterate through all animals
        amount = animal[0]
        name = animal[1]
        noise = animal[2]
        format1 = f'Verse :{count}\n'   #formatting strings
        format2 = f'Old MacDonald had a farm\n'
        format3 = f'E-I-E-I-O\n'
        format4 = f'And on his farm he had {amount} {name}\'s\n'
        format5 = f'With a {noise} {noise} there\n'
        format6 = f'And a {noise} {noise} here\n'
        format7 = f'Here a {noise},there a {noise}\n'
        format8 = f'Everywhere a {noise} {noise}\n'
        string =str(format1+format2+format3+format4+format3+format5+format6+format7+format8+format2+format3)
        vfile.write(string+"\n")    
        print(string)
        count+=1
    vfile.write("Old MacDonald has a total of {0} animals".format(count-1))
    print(f"Old MacDonald had a total of {result} animals")


try:
    file = open('animals.txt','r')
except FileNotFoundError as a:
    print(a)
contents = file.readlines()

animals_list = []
for line in contents:
    line = line.rstrip("\n")
    animals_list.append(line.split(" "))

file.close()

try:
    vfile = open("verses.txt","w+")
except:
    pass
write_verse(vfile,animals_list)
vfile.close()

这是我 运行 时发生的事情 -

节 :1 老麦克唐纳有个农场 E-I-E-I-O 在他的农场里,他养了 2 头猪 E-I-E-I-O 那里有一个问题 还有一个问题 这里有一个问题,那里有一个问题 到处都是 oink oink 老麦克唐纳有个农场 E-I-E-I-O

节 :2 老麦克唐纳有个农场 E-I-E-I-O 在他的农场里,他养了 3 只鸭子 E-I-E-I-O 那里嘎嘎嘎嘎 还有这里的江湖江湖 这里有江湖,那里有江湖 处处是嘎嘎嘎嘎 老麦克唐纳有个农场 E-I-E-I-O

诗句 :3 老麦克唐纳有个农场 E-I-E-I-O 在他的农场里,他有 4 匹马 E-I-E-I-O 那里有嘶嘶声 嘶嘶声在这里 这里嘶嘶声那里嘶嘶声 到处都是嘶嘶声 老麦克唐纳有个农场 E-I-E-I-O

诗句 :4 老麦克唐纳有个农场 E-I-E-I-O 在他的农场里,他养了 5 只羊羔 E-I-E-I-O 那里有咩咩声 咩咩在这里 这里咩那里咩 处处咩咩 老麦克唐纳有个农场 E-I-E-I-O

诗句 :5 老麦克唐纳有个农场 E-I-E-I-O 在他的农场里,他养了 6 只鸡 E-I-E-I-O 那里咯咯咯咯 这里咯咯咯咯 这里咯咯咯,那里咯咯咯 处处咯咯咯咯 老麦克唐纳有个农场 E-I-E-I-O

节数 :6 老麦克唐纳有个农场 E-I-E-I-O 在他的农场里,他养了 7 条狗 E-I-E-I-O 那里有汪汪汪 和这里的汪汪汪 这里汪汪那里汪 到处都是汪汪汪 老麦克唐纳有个农场 E-I-E-I-O

诗句 :7 老麦克唐纳有个农场 E-I-E-I-O 在他的农场里,他养了 8 只猫 E-I-E-I-O 那里有喵喵声 在这里喵喵叫 这里有喵喵,那里有喵喵 到处都是喵喵 老麦克唐纳有个农场 E-I-E-I-O

第 8 节 老麦克唐纳有个农场 E-I-E-I-O 在他的农场里,他有 9 头奶牛 E-I-E-I-O 那里有哞哞声 还有这里的哞哞 这里哞哞,那里哞哞 到处都是哞哞 老麦克唐纳有个农场 E-I-E-I-O

老麦克唐纳共有0只动物

进程已完成,退出代码为 0

您正在打印 result,但 result 计算不正确。你的代码有很多问题,有人已经指出了如何解决这个问题。因此,相反,我将提出一些建议,以编写更清晰、更有条理的代码,从而使调试问题变得更加容易:

# Use a template literal string formatted almost exactly as 'WYSIWYG'
VERSE = """
Verse: {verse}
Old MacDonald had a farm
E-I-E-I-O
And on his farm he had {amount} {animal}s
With a {noise} {noise} here
And a {noise} {noise} there
Here a {noise} there a {noise}
Everywhere a {noise} {noise}
Old MacDonald had a farm
E-I-E-I-O
"""


# Separate helper function to read in your data
def read_file(path):
    data = []
    with open(path, "r") as file:
        for line in file.readlines():
            amount, animal, noise = line.strip().split()
            data.append({"animal": animal, "noise": noise, "amount": int(amount)})
    return data


# Write any number of verses given a list of animals
def sing_old_macdonald(animals):
    song = ""
    total = 0
    for verse, animal in enumerate(animals, 1):
        song += VERSE.format(verse=verse, **animal)
        total += animal["amount"]
    return song, total


# Main script
if __name__ == "__main__":
    animals = read_file("animals.txt")
    song, total_animals = sing_old_macdonald(animals)
    print(song)
    print(f"Old MacDonald has {total_animals} animals on his farm")

修剪后的输出:

.
.
.

Verse: 8
Old MacDonald had a farm
E-I-E-I-O
And on his farm he had 9 cows
With a moo moo here
And a moo moo there
Here a moo there a moo
Everywhere a moo moo
Old MacDonald had a farm
E-I-E-I-O

Old MacDonald has 44 animals on his farm

vfile 变量是一个指向空文件(您将输出写入的文件)的文件对象,因此当您执行 sum(map(int, vfile)) 时,它会产生 0,因为它正在求和零线。

您的 animals 变量中已经有了每只动物的数量,因此要解决此问题,您可以替换为:

with open('animals.txt', 'r') as f:
    result = sum(map(int, vfile))

有了这个:

result = sum(int(animal[0]) for animal in animals)