简体   繁体   English

从带有字符串和数字的文本文件中读取元组列表

[英]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: 正如其他人所评论的,您可以使用ast.literal_eval()函数,因为您的数据似乎采用与Python文字相同的格式:

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)]

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

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