从文本文件计算重复负载 Python

calculating duplicates payload from text file Python

我正在尝试从文本文件计算人们的分数条目:

埃西 5 皮耶塔里 9 埃西 2 皮塔里 10 皮耶塔里 7 前 25 埃西 1

预期输出:

参赛者得分: 前 25 埃西 8 皮耶塔里 26

我的输出: 前 25 埃西 11 皮耶塔里 77

我的代码计算有误!

我的代码是:

def reading():
"""
reads input file name and open it, split lines from text in 2.
do the calculation, print out the dictionary
:return: dict.
"""
file1 = input("Enter the name of the score file: ")
read_file = open(file1, mode="r")
dict = {}

for line in read_file:
    # Remove the character(s) that end the line.
    line = line.rstrip()

    # Split the line in two.
    name, score = line.split(" ")

    # Add a new entry to the phone book.
    if name not in dict:
        dict[name] = score

    elif name in dict:
        dict[name] = score + score

#Close the file.
read_file.close()

#print dict sorted
for p in sorted(dict.keys()):
    print(f"{p} {dict[p]}")

def main():
    #the function call
    reading()

if __name__ == "__main__":
        main()

试试下面的方法。 (zz.txt 保存您的数据)

代码中需要注意的几点:
@不要命名你的数据结构变量'dict'
@打开文件时使用'with'
@尽可能使用 defaultdict

from collections import defaultdict

data = defaultdict(int)
with open('zz.txt') as f:
    lines = [l.strip() for l in f.readlines()]
    for line in lines:
        fields = line.split(' ')
        data[fields[0]] += int(fields[1])
print(data)

输出

defaultdict(<class 'int'>, {'essi': 8, 'pietari': 26, 'aps': 25})

你的问题是你在这里拆分的时候

# Split the line in two.
name, score = line.split(" ")

您得到两个字符串,当您将它们添加到行中时会出现意外行为

dict[name] = score + score

您可以将分数字符串转换为整数。添加此行,它将解决您的问题

    # Split the line in two.
    name, score = line.split(" ")
    score = int(score)

也改变你的行来更新你的字典

dict[name] += score