0

我有一个包含大量实验结果的大文本文件来搜索需要编译的特定数据。文本文件包含许多不同实验的结果,我需要将每个实验的数据保存在一起。

例如(不是实际数据)

Object 1

The colour of the object is blue.
The size of the object is 0.5 m^3
The mass of the object is 0.8 g

Object 2

The colour of the object is pink.
The size of the object is 0.3m^3
etc.

我知道我想要的值在哪里,因为我可以在文本中搜索我知道将出现在数据所在行上的特定短语。

我想到的一种方法是在文件中搜索每个特定行(我正在寻找两个不同的变量),并将所需的值添加到列表中。然后,我将为每个对象创建一个字典,假设每个列表中的相同数字将是来自同一对象的数据。

例如

variable_one = []
variable_two = []

def get_data(file):
    with open("filename.txt", "r") as file:
        for line in file:
            if "The colour" in line:
                variable_one.append(line.split()[6]) 
            if "The mass" in line:
                variable_two.append(line.split()[6]) 

        file.close()

或者,搜索文件并创建一个列表,每个条目是来自不同对象的数据部分,然后从列表中的不同项目中搜索每个对象的两个变量 - 最终再次存储每个对象的值字典中的对象。

我想知道的是,是否有比我的想法更有效/更好的方法来做到这一点?

4

2 回答 2

0

除了我在评论中提到的区域以及如果您的行短于 6 个单词,索引会导致错误之外,您在那里的操作方式对我来说总体上看起来不错。

于 2013-08-07T15:15:42.643 回答
0

这是一种仅使用一个列表并使用较少“附加”和较少“输入”的替代方法,因此应该更有效。

variables = []

with open('filename.txt') as input:
    colour = mass = ''
    for line in input:
        fields = line.split()
        if len(fields)>6:
            value = fields[6]
            if 'The colour' in line:
                colour = value
            elif 'The mass' in line:
                mass = value
        elif line.startswith('Object'):
            variables.append((colour, mass))
            colour = mass = '' # may not be needed.
del(variables[0])
于 2013-08-07T16:53:10.550 回答