Read tuples from text file

橙三吉。 提交于 2020-01-14 14:46:07

问题


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)

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.

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.


回答1:


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)

output:

[(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)]

Or even better:

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)



回答2:


Here's a simple way without using any libraries:

tuples = []
for t in open('input.txt').read().split():
    a, b = t.strip('()').split(',')
    tuples.append((int(a), int(b)))

List comprehension equivalent:

[tuple(int(i) for i in t.strip('()').split(',')) for t in open('input.txt').read().split()]


With input.txt being the data provided in the question, this is the output:

[(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)]



回答3:


You can try this one, although it does not use the numpy library:

from ast import literal_eval as createTuple

tupleList = []

with open("test.txt","r") as infile:
    for line in infile:
        line = line.split()
        for l in line:
            tupleList.append(createTuple(l))

print(tupleList)

Format of input file:

(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)

Output (list of tuples):

[(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)]


来源:https://stackoverflow.com/questions/48094176/read-tuples-from-text-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!