简体   繁体   中英

Python - Reading a text file into dictionary

I recently started programming with Python and i've encountered quite a big problem with one of my functions. I'm trying to take data from a text file in the form of a list, into a dictionary in Python. The format of the text file is consistently formatted as is displayed below:

@text {
    n = "test1",
    r = ["B:1", "G:2", "H:3", "O:4", "S:5", "W:6"],
    t = ["G:1","H:2"]
}

Using the three keys: n, r and t; how would I go about reading their values from the text file into my dictionary using Python?

So far, I have managed to develop the following code with no success, not knowing where i've gone wrong despite attempting to research this all over the web.

f = open('text.txt', 'r')
newDict = {}
for line in f:
    n, r, t = line.strip().split('=')
    newDict[k.strip()] = v.strip()

Am I along the right lines with this or completely off the mark? The whole concept of reading multiple keys and values into a dictionary from a text file has me completely confused when it comes to the process of importing/converting the file.

Any help with this would be greatly appreciated - thank you in advance.

You can do:

for line in f:
    listedline = line.strip().split('=') # split around the = sign
    if len(listedline) > 1: # we have the = sign in there
        newDict[listedline[0]] = listedline[1]

However, what do you want to do with the data stored in this dict? It will store everything as strings so your list will be a big string. If you need more refined data, it's not too hard but you will have to tell us what it is you want to accomplish with this dict.

If you can't control your input text files, you can parse them with (potentially unsafe, so make sure of input) eval , see demo:

source = """@text {
    n = "test1",
    r = ["B:1", "G:2", "H:3", "O:4", "S:5", "W:6"],
    t = ["G:1","H:2"]
}"""
nrt = ' '.join(source.splitlines()[1:4])

here nrt is space-joined lines with n , r and t definition. To make it valid python code, wrap with dict(..) , and eval result:

obj_code = 'dict({})'.format(nrt)
result = eval(obj_code)

And finally:

>>> result
{'r': ['B:1', 'G:2', 'H:3', 'O:4', 'S:5', 'W:6'], 't': ['G:1', 'H:2'], 'n': 'test1'}

Not sure if this is the case, but if you're outputting said text file, and trying to read it back in later, you can use Pickle instead of simply writing to a text file. This allows you to output an object and read it back in later, aka object serialization.

As an example:

import pickle

#to save object
pickle.dump(yourDict, open(yourFile, 'wb'))

#to load it back:
yourDict = pickle.load(open(yourFile, 'rb'))

Here's a crude attempt:

text = """
@text {
    n = "test1",
    r = ["B:1", "G:2", "H:3", "O:4", "S:5", "W:6"],
    t = ["G:1","H:2"]
}"""

import re
from collections import defaultdict
from ast import literal_eval

items = defaultdict(dict)
for name, lines in re.findall(r'(@\w+) {\s*(.*?)\s*}', text, flags=re.S):
    for var, val in re.findall(r'\s*(\w+)\s*=\s*(.*?),?$', lines, flags=re.M):
        items[name][var] = literal_eval(val)

# defaultdict(<type 'dict'>, {'@text': {'r': ['B:1', 'G:2', 'H:3', 'O:4', 'S:5', 'W:6'], 't': ['G:1', 'H:2'], 'n': 'test1'}})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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