[英]How do I add tuples from a txt file to a list without the quotation marks? Python
好的,所以我有一个类似tuples的txt文件:
("Item1", 2, 3, 4)
("Item2", 3, 4, 5)
("Item3", 4, 5, 6)
每个元组将被设置在它自己的行上,并且完全类似于项0是字符串而另外3个是数字的元组。 现在对于我遇到麻烦的部分。 基本上,我想阅读元组并将其添加到列表中。 这是我想出的:
with open('data.txt', 'r', encoding='utf-8') as file:
lst = [line.strip() for line in file]
它将每个项目添加到列表中。 但是,每个项目在过程中都会转换为字符串。 我怎样才能获得元组值。
你可以使用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]
这可以安全地将字符串计算为元组。 它比使用eval()
更安全。
您可能还想考虑使用pickle
模块来编写和读取此类数据。 这是一个例子:
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
使用正则表达式?
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.