Skip to main content
 首页 » 编程设计

python之从文件中读取一组元组编号

2025年05月04日14lovecherry

我有一个文件,前两行如下所示:

(1,233)(44,444)(2323,545)(0,0)(22,2)(5,0)(222,2)(0,5)(12,2)(22,3) 
(0,223)(44,424)(123,545)(0,1)(42,2)(5,0)(52,2)(0,6)(17,4)(3,3) 

我想读取每个元组并获取每个数字(不带逗号和括号)。我是这样读的:

file = filedialog.askopenfilename(filetypes=[("Text files","*.txt")]) 
if file is None: 
    return False 
 
with open(file, 'r') as f: 
    lines = f.read().split("\n") 
    firstLine = lines[0] 
    secondLine = lines[1] 
 
    # Run loop here to get the tuple values 
    # firstNum = tuple[0] 
    # secondNum = tuple[1] 
 
    # Go to next line and do the same 

我怎样才能做到以上几点?任何帮助将不胜感激。

请您参考如下方法:

我会选择正则表达式:

[(int(x), int(y)) for x,y in re.findall(r"\((\d+),\s*(\d+)\)", line)] 
# [(1, 233), (44, 444), (2323, 545), (0, 0), (22, 2), (5, 0), (222, 2), ...] 

另一个有趣的解决方案是通过在对之间插入逗号将行转换为有效的 Python 元组,然后应用 ast.litereal_eval:

list(ast.literal_eval(line.replace(")", "),"))) 
# [(1, 233), (44, 444), (2323, 545), (0, 0), (22, 2), (5, 0), (222, 2), ...]