簡體   English   中英

從帶有字符串和數字的文本文件中讀取元組列表

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

我有一個文本文件,其中每一行代表序列挖掘操作的結果。 因此,每個元組中的第一個元素是字符串(字母)的元組,第二個元素是頻率(整數)。

如何將這些內容從文本文件讀回原始格式? 格式如下,直接從文本文件中復制。...似乎找不到任何類似的示例,但是必須有一種方法可以輕松地做到這一點。

(('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) 

正如其他人所評論的,您可以使用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)

輸出:

[(('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