繁体   English   中英

从文本文件中读取元组

[英]Read tuples from text file

我需要从txt中读取元组。 我尝试使用numpy(使用genfromtxt),但它不起作用(或者至少,我不知道如何)。 这是我的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我有这个:

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

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

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

这是一种不使用任何库的简单方法:

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

列表理解等效:

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


使用input.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库:

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)

输入文件格式:

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

输出(元组列表):

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM