简体   繁体   English

读取txt文件数据作为字典

[英]Read txt file data as dictionary

I am new to python. 我是python的新手。 I have a txt file which contains input data for a 3D model: 我有一个txt文件,其中包含3D模型的输入数据:

...
# comments
rfk = [1e-5, 1e-7, 1e-1]
rsig = [0.0005]
# comments
lengths = [[13,13,1.6],[13,13,1.6],[13,13,1.6]]
...

I guess the best way to extract the data for further processing is to save them into dictionaries - like this: 我猜想提取数据进行进一步处理的最好方法是将它们保存到字典中,如下所示:

data1 = {rfk:[1e-5, 1e-7, 1e-1], rsig:[0.0005], lengths:[[13,13,1.6],[13,13,1.6],[13,13,1.6]]}

I now struggle a little bit with reading the file and saving the data (by ignoring the comments) like in my example as dictionaries. 我现在在读取文件和保存数据(忽略注释)方面有些挣扎,就像在我的示例中作为字典一样。 My approach for reading the data from the file was like this: 我从文件中读取数据的方法是这样的:

for line in open("myfile.txt"):
    li=line.strip()
    if not li.startswith("#"):        
        # what to do here?

We can use ast.literal_eval to evaluate the right hand side into Python objects 我们可以使用ast.literal_eval评估右侧的Python对象

from ast import literal_eval

with open('myfile.txt') as file:
    d = {}
    for line in file:
        line = line.strip()
        if not line.startswith('#'):
            key, value = map(str.strip, line.split('='))
            d[key] = literal_eval(value)

For your example data, d is then 对于您的示例数据,则d

{'rfk': [1e-05, 1e-07, 0.1], 'rsig': [0.0005], 'lengths': [[13, 13, 1.6], [13, 13, 1.6], [13, 13, 1.6]]}

You can use the string method partition * to seperate your data to key and value for your dictionary, 您可以使用字符串方法partition *将数据分为字典的键和值,
The string method strip to clean up your key's string from leading and tailing spaces 字符串方法strip可从前导空格和尾部空格清除键的字符串
And then the built-in function eval to extract the pythonic object from the value's string, as such: 然后,内置函数eval从值的字符串中提取pythonic对象,如下所示:

with open('myfile.txt') as file:
    d = {}
    for line in file:
        line = line.strip()
        if not line.startswith('#'):
            key, _ ,value = line.partition('=')
            d[key.strip()] = eval(value)

* partition splits your string in the first occurance of your delimiter (which is '=' in this case) * partition在分隔符的第一个出现时将您的字符串分割(在这种情况下为'=')
and returns a list of [leading string, delimiter, following string] 并返回一个list的[前导字符串,分隔符,下面的字符串]

You can treat the at as json and add a few safety checks: 您可以将at视为json并添加一些安全检查:

import json

data = {}
with open('thefile.txt') as fobj:
    for raw_line in fobj:
        line = raw_line.strip()
        if line and not line.startswith('#'):
            try:
                key, values = line.split('=', 1)
            except ValueError:
                print('skipping invalid line:')
                print(line)
            try:
                data[key.strip()] = json.loads(values)
            except json.JSONDecodeError
                print('skipping invalid line (no JSON):')
                print(line)

for your example data contains: 对于您的示例data包含:

{'lengths': [[13, 13, 1.6], [13, 13, 1.6], [13, 13, 1.6]],
 'rfk': [1e-05, 1e-07, 0.1],
 'rsig': [0.0005]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM