从.txt文件(python)添加具有不同值的相同变量

2024-09-30 20:23:02 发布

您现在位置:Python中文网/ 问答频道 /正文

用python

例如,我在一个.txt文件中有变量X、Y和Z,格式如下:

random text
random text
X: 123
Y: 300
random text
X: 22
Y: 34
Z 458.000 random text
random text

我如何将这些值添加到适当的变量中?所以我得到了X = 123 + 22Y = 300 + 34

目前我有:


with open('F:/Software/ogamebot/expocounter/allexpo.txt', 'r') as file:
        expo_file = file.read()

    print(expo_file)

但从这里继续下去的最佳方式是什么


Tags: 文件texttxtreadas格式withsoftware
2条回答

你想做什么还不完全清楚。我的解释是:您有一组预定义的命名变量。如果文件中的一行以变量的名称开头,则需要向该变量添加后续值。具体来说,变量名和给定值之间会有一些空格。以下代码实现此解释:

with open('F:/Software/ogamebot/expocounter/allexpo.txt', 'r') as file: # open the file
    lines = list(file) # get a list of lines of text
    variables = {'X': 0, 'Y': 0, 'Z': 0} # define our variables in a dictionary (all initially 0)
    for line in lines: # iterate over each line
        for var_name in variables:
            # for each variable, check if the line begins with that variable name
            if line.startswith(var_name): 
                variables[var_name] += float(line.split()[1])
                # if so, add the value to that variable
                # line.split() splits the line into elements based on whitespace
                # we then take the second element, and convert it to a number
    print(variables) # output the results

这当然适用于您的特定示例,但这是您通常想要的吗?例如,变量名和值之间是否总是有空格?还请注意,这段代码不会将值加载到python变量中(即X存储为variables['X'],而不仅仅是X)-这将更难以整洁的方式完成

如果您在文本文件中有一个固定的变量定义模式,比如VAR: VALUE,那么下面是我的代码,用于在不基于预定义变量名称的情况下计算它

来源数据:

# allexpo.txt

random text
random text
X: 123
Y: 300
A: 101
John: 200
random text
X: 22
Y: 34
Z: 458.000 random text
John: 400
random text

代码如下:

步骤0

从文件中获取数据

with open('allexpo.txt', 'r') as file:
    expo_file = file.read()

print(expo_file)

步骤1

import re
arr = [i.split(': ') for i in '.'.join(re.findall('[a-zA-Z0-9]*: [0-9]*', expo_file)).split('.')]
print(arr)

# it gives you structure like this:
# [['X', '123'], ['Y', '300'], ['A', '101'], ['John', '200'], ['X', '22'], ['Y', '34'], ['Z', '458'], ['John', '400']]

步骤2

arr1 = [(i[0], float(i[1])) for i in arr]
print(arr1)

# it gives you structure like this:
# [('X', 123.0), ('Y', 300.0), ('A', 101.0), ('John', 200.0), ('X', 22.0), ('Y', 34.0), ('Z', 458.0), ('John', 400.0)]

步骤3

var = {k:sum([v[1] for v in arr1 if v[0] == k]) for k in set([i[0] for i in arr1]) }
print(var)

# it gives you desire result:
# {'Z': 458.0, 'John': 600.0, 'Y': 334.0, 'X': 145.0, 'A': 101.0}

最终它是一个三行代码!:)

相关问题 更多 >