简体   繁体   中英

Reading a list of tuples from a text file with strings and numbers

I have a text file where each line represents the results from a sequence mining operation. So the first element in each tuple is a tuple of strings (letters), and the second element is the frequency (int).

How can I read these back from the text file into the original format? Format as follows, copied directly from the text file.... Can't seem to find any similar examples out there but there's got to be a way to do this easily.

(('a',), 30838057)
(('a', 'b'), 23151399)
(('a', 'b', 'c'), 13865674)
(('a', 'b', 'c', 'e'), 8979035)
(('a', 'b', 'c', 'e', 'f'), 6771982)
(('a', 'b', 'c', 'e', 'f', 'g'), 4514076)
(('a', 'b', 'c', 'e', 'f', 'g', 'h'), 2403374) 

As other have commented you can use the ast.literal_eval() function since your data appears to be formatted the same a Python literals:

import ast
from pprint import pprint


filename = 'tuples_list.txt'

tuple_list = []
with open(filename) as inp:
    for line in inp:
        values = ast.literal_eval(line)
        tuple_list.append(values)

pprint(tuple_list)

Output:

[(('a',), 30838057),
 (('a', 'b'), 23151399),
 (('a', 'b', 'c'), 13865674),
 (('a', 'b', 'c', 'e'), 8979035),
 (('a', 'b', 'c', 'e', 'f'), 6771982),
 (('a', 'b', 'c', 'e', 'f', 'g'), 4514076),
 (('a', 'b', 'c', 'e', 'f', 'g', 'h'), 2403374)]

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