Home > database >  How can I convert this text file into a python dictionay?
How can I convert this text file into a python dictionay?

Time:11-16

So I have this text file

(1, 15), 'indice3 = [4, 5, 6]'
(7, 1), "indice1 = {3: 'A B C'}"
(11, 7), "indice4 = '(1, 2)'"
(11, 17), 'typage = mode de déclaration des types de variable'
(23, 5), "indice5 = '(3, 4)'"
(25, 1), '27 * 37 = 999'

As you can see, there's at first coordinates and then a text.

Here's an example of what it would look like at the end (for the first two elements)

{
    (1,15): "indice3 = [4, 5, 6]",
    (7, 1): "indice1 = {3: 'A B C'}"
}

I know that I should start by reading the file (f = open("dico_objets.txt", "r")) and then read it line by line but I don't know how to split it correctly.

CodePudding user response:

Try to use ast.literal_eval:

from ast import literal_eval


out = []
with open("your_file.txt", "r") as f_in:
    for line in map(str.strip, f_in):
        if line == "":
            continue
        out.append(literal_eval(f"[{line}]"))

print(dict(out))

Prints:

{
    (1, 15): "indice3 = [4, 5, 6]",
    (7, 1): "indice1 = {3: 'A B C'}",
    (11, 7): "indice4 = '(1, 2)'",
    (11, 17): "typage = mode de déclaration des types de variable",
    (23, 5): "indice5 = '(3, 4)'",
    (25, 1): "27 * 37 = 999",
}

CodePudding user response:

you can use find() on each line. Read your file line by line and do something like below

split_point = line.find(',', line.find(',') 1)
out_dict[line[:split_point]] = line[split_point:]
  • Related