文本文件python中每行的计数值

文本文件python中每行的计数值,python,file,Python,File,我想我已经接近我想要的了,但我仍然是一个乞丐,所以我不知道这是否是最好的方式。假设我们有一个包含数百行的文件,在每行的末尾有一个我想要计算的值。对我来说,用一行代码编写所有程序似乎很复杂,所以我更喜欢一步一步地进行。假设我们有一个文件,其行如下: Type of line 1: 10 Type of line 1: 5 Type of line 1: 15 Type of line 2: 50 Type of line 2: 25 Type of line 2: 5 Type of line 3

我想我已经接近我想要的了,但我仍然是一个乞丐,所以我不知道这是否是最好的方式。假设我们有一个包含数百行的文件,在每行的末尾有一个我想要计算的值。对我来说,用一行代码编写所有程序似乎很复杂,所以我更喜欢一步一步地进行。假设我们有一个文件,其行如下:

Type of line 1: 10
Type of line 1: 5
Type of line 1: 15
Type of line 2: 50
Type of line 2: 25
Type of line 2: 5
Type of line 3: 1
Type of line 3: 14
Type of line 3: 2
因为有各种类型的线,所以我想得到的是出现在同一类型线中的那些值的总和。例如,输出应如下所示:

Type of line 1: 30
Type of line 2: 80
Type of line 3: 17
行的类型它只是一个字符串

因此,为了实现这一点,我首先逐行读取文件,并使用“:”字符分割每一行。然后,我将这些拆分的行保存在一个变量中,以便稍后调用其元素,并使用相同类型的行对这些值求和。我知道,因为它是一个文件,其中的行是字符串,为了使用值进行操作,它们必须被视为int,所以它应该类似于int(y[1]),但我不确定。有没有建议我是否走上了正确的道路? 以下是我迄今为止所做的尝试:

with open('file.txt','r') as f:
    for line in f:
        y = line.split(':')
        ...

您可以使用
itertools.groupby
按行值对行进行分组,然后对每行的尾随数字求和:

import itertools
import re
file_data = [i.strip('\n') for i in open('filename.txt')]
new_data = [[a, list(b)] for a, b in itertools.groupby(sorted(file_data, key=lambda x:re.findall('(?<=line\s)\d+', x)), key=lambda x:re.findall('(?<=line\s)\d+', x))]
final_results = ['Type of line {}: {}'.format(a, sum(int(re.findall('\d+$', i)[0]) for i in b)) for [a], b in new_data]

这是一个使用标准数据类型的基本答案,可能不是最有效的方法,但它将帮助您学习python的基础知识

dict是中间数据结构的良好选择, 因为不能有多个同名键。我们用这个来总结你的行

    output = dict()  

    with open("file_name", "r") as file:
        for line in file.readlines(): 
            line_name, value = line.split(":")
            value.strip()  # Strip the new line character
            if line_name in output.keys():  # Test to see if we see this line before
                output[line_name] += int(value)  #  augmented addition operator
            else:
                output[line_name] = int(value) # line not found assign basic value

    for key, value in output.items():  # format the output in the way you wanted
        print("The sum of %s is %s" % (key, value))
输出:

['Type of line 1: 30', 'Type of line 2: 80', 'Type of line 3: 17']
The sum of Type of line 2 is 80
The sum of Type of line 1 is 30
The sum of Type of line 3 is 17

欢迎来到StackOverflow。请按照您创建此帐户时的建议,阅读并遵循帮助文档中的发布指南。在这里申请。StackOverflow不是设计、编码、研究或教程服务。有很多教程和堆栈溢出问题,展示了如何读取和转换这样的数据。你怎么被卡住了?你怎么不确定某个东西是否有效?当你尝试它的时候发生了什么?对不起,如果我问了一个非主题的问题,我只是阅读文档和如何要求规则。我下次会考虑。我会试着看看这个问题是否已经得到了回答。很抱歉