从文本文件中读取元组 [英] Read tuples from text file

查看:41
本文介绍了从文本文件中读取元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从 txt 中读取元组.我尝试使用 numpy(使用 genfromtxt)但它没有用(或者至少,我不知道如何).这是我的txt:

I need to read tuples from a txt. I tried with numpy (using genfromtxt) but it didn't work (or at least, I don't know how). This is is my txt:

(0,0) (0,0) (1,0) (2,3)
(1,0) (1,1) (1,1) (3,3)
(2,0) (1,2) (2,1) (4,4)
(3,0) (2,2) (3,1) (5,5)

我想一一阅读此列并获取元组列表:尝试使用 numpy 我有这个:

I want to read one by one this columns and get a list of tuples: Trying with numpy I have this:

import numpy as np
File = np.genfromtxt('file.txt',delimiter=' ', dtype= tuple)

但它返回一个包含字节类型元素的列表.

But it returns a list of lists with bytes type elements.

显然我可以改变数据在txt中的存储方式.我只需要从 txt 中获取元组列表(或列表列表).

Obviously I can change the way the data is stored in the txt. I just need to get a list of tuples (or a list of lists) from a txt.

推荐答案

你也可以在这里尝试正则表达式:

You can try regular expression too here:

import re
pattern='\((\d+,\d)\)'
with open('demo.txt','r') as f:
    for line in f:
        data=re.findall(pattern,line)
        data_1=[]
        for item in data:
            data_1.append(tuple(map(lambda x:int(x),item.split(','))))
        if data_1:
            print(data_1)

输出:

[(0, 0), (0, 0), (1, 0), (2, 3)]
[(1, 0), (1, 1), (1, 1), (3, 3)]
[(2, 0), (1, 2), (2, 1), (4, 4)]
[(3, 0), (2, 2), (3, 1), (5, 5)]

甚至更好:

import re
pattern='\((\d+,\d)\)'
with open('demo.txt','r') as f:
    for line in f:
        data=re.findall(pattern,line)
        data_1=[tuple(map(lambda x:int(x),item.split(','))) for item in data]
        if data_1:
            print(data_1)

这篇关于从文本文件中读取元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆