如何合并文本文件中的行?

克里斯

我有一个看起来像这样的文本文件:

100 Spam
250 Spam
50  Spam
20  Eggs
70  Eggs

现在,我想将这些行合并到一个新文件中,使其看起来像这样:

300 Spam
90  Eggs

我将文件逐行读入列表。现在,我像这样遍历列表中的每个项目:

new_list = []
j = 1
for i in range(len(old_list)):
       new_list.append("")
       if old_list[i][4:] == old_list[i-j][4:]:
          new_list[i-j][:4] = str(int(old_list[i][:4].strip()) + int(old_list[i-j][:4].strip())).ljust(4)
          new_list[i-j][4:] = old_list[i-j][4:]
          j += 1
       else:
          new_list[i-j] = old_list[i-j]

我遇到了两个问题:

  1. 我收到一个类型错误,说我不能分配给字符串
  2. 即使没有错误,当要添加多于2行时,我也无法获得正确的总和,因为在循环中,我会覆盖总和。我将需要以某种方式存储此总和,但我无法想到一种优雅的方式来实现此目的。

我是编程新手,所以也许有更好的方法可以一起解决问题?

鲍里斯
result = {}

with open("your_file.txt") as infile:
    for line in infile:
        amount, food_item = line.split()
        result[food_item] = result.get(food_item, 0) + int(amount)

print(result)  # {'Spam': 400, 'Eggs': 90}

然后您可以写出result到新文件

with open("some_other_file.txt") as outfile:
    for food_item, amount in result.items():
        outfile.write(f"{amount} {food_item}\n")

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章