简体   繁体   English

如何将txt文件中的元组添加到没有引号的列表中? 蟒蛇

[英]How do I add tuples from a txt file to a list without the quotation marks? Python

Ok, so I have a txt file of tuples like such: 好的,所以我有一个类似tuples的txt文件:

("Item1", 2, 3, 4)
("Item2", 3, 4, 5)
("Item3", 4, 5, 6)

Each tuple will be set on its own line and exactly like that where item 0 is a string and the other 3 are numbers. 每个元组将被设置在它自己的行上,并且完全类似于项0是字符串而另外3个是数字的元组。 Now for the part I am having trouble with. 现在对于我遇到麻烦的部分。 Basically, I want to read the tuple and add it to a list. 基本上,我想阅读元组并将其添加到列表中。 Here is what I came up with: 这是我想出的:

with open('data.txt', 'r', encoding='utf-8') as file:
     lst = [line.strip() for line in file]

It adds each item to the list. 它将每个项目添加到列表中。 However, each item is converted to a string in the process. 但是,每个项目在过程中都会转换为字符串。 How would I get just the tuple value. 我怎样才能获得元组值。

You can use ast.literal_eval() : 你可以使用ast.literal_eval()

import ast
with open('data.txt', 'r', encoding='utf-8') as file:
    lst = [ast.literal_eval(line.strip()) for line in file]

This safely evaluates the string to a tuple. 这可以安全地将字符串计算为元组。 It is safer than using eval() . 它比使用eval()更安全。


You may also want to consider using the pickle module for writing and reading such data. 您可能还想考虑使用pickle模块来编写和读取此类数据。 Here's an example: 这是一个例子:

import pickle
with open('a.txt', 'w') as myfile:
    pickle.dump([("Item1", 2, 3, 4), ("Item2", 3, 4, 5), ("Item3", 4, 5, 6)], myfile)

with open('a.txt', 'rb') as myfile2: # Open in bytes
    lst = pickle.load(myfile2)
    for tup2 in lst:
        print tup2

Use regex? 使用正则表达式?

def main():
    filename = sys.argv[1]
    fp = open(filename, 'r') # TODO error handling
    text = fp.read()
    fp.close()

    matches = re.findall(r'\(\"([^"]+)\",\s+(\d+),\s+(\d+),\s+(\d+)\)', text)
    for match in matches:
        (itemname, num1, num2, num3) = match
        print itemname, num1, num2, num3
        # Do whatever you want with them

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

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