【问题标题】:How do I add tuples from a txt file to a list without the quotation marks? Python如何将 txt 文件中的元组添加到不带引号的列表中? Python
【发布时间】:2013-09-20 00:19:41
【问题描述】:

好的,所以我有一个这样的元组 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]

它将每个项目添加到列表中。但是,每个项目都会在此过程中转换为字符串。我将如何获得元组值。

【问题讨论】:

    标签: python string file list tuples


    【解决方案1】:

    你可以使用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
    

    【讨论】:

    • 哈哈,谢谢。我曾经尝试做类似的事情: [ast.literal_eval(line.strip() for line in file)] 无法弄清楚为什么它不能正常工作。非常感谢。
    • @MarshallLyon 看起来你把第二个括号放错了地方。把它带回来,让它在line.strip()之后
    • @MarshallLyon 另外,别忘了accept the answer :)
    【解决方案2】:

    使用正则表达式?

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-09
      • 1970-01-01
      • 1970-01-01
      • 2021-04-26
      • 2019-02-10
      • 1970-01-01
      • 2020-10-15
      • 1970-01-01
      相关资源
      最近更新 更多