Read tuples from text file

前端 未结 3 879
失恋的感觉
失恋的感觉 2021-01-14 12:39

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)         


        
3条回答
  •  感动是毒
    2021-01-14 13:05

    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)
    

提交回复
热议问题