简体   繁体   English

我需要从文件中获取x,y坐标的元组并将其添加到列表中

[英]I need to get tuples of x,y coordinates from a file and add it to a list

So my txt file looks like this: 所以我的txt文件看起来像这样:

68,125
113,69
65,86
108,149
152,53
78,90
54,160
20,137
107,90
48,12

I need to read these files and then put it into a list of x and y coordinates tuples. 我需要阅读这些文件,然后将其放入x和y坐标元组的列表中。

My output should be 我的输出应该是

[(68, 125), (113, 69), (65, 86), (108, 149), (152, 53), (78, 90), (54, 160), (20, 137), (107, 90), (48, 12)] 

I am stuck on how to do this. 我被困在如何做到这一点上。 I need to use basic python only. 我只需要使用基本的python。

Edit: 编辑:

My attempt so far is this 到目前为止,我的尝试是

numbers = []
input_file = open(filename,'r')
numbers_list = input_file.readlines()
input_file.close()
for i in numbers_list:
    numbers += [i]
return numbers

My output returns as this: 我的输出返回如下:

['68,125\n', '113,69\n', '65,86\n', '108,149\n', '152,53\n', '78,90\n', '54,160\n', '20,137\n', '107,90\n', '48,12\n']

How do I get rid of the '\\n' and also how can I put each individual element in the list into a tuple. 如何摆脱'\\ n'以及如何将列表中的每个元素放入一个元组。 Thank you. 谢谢。 My mistake for not adding in my attempt. 我没有加入尝试的错误。

Here are 3 and 2 line answers: 这是3和2行答案:

with open("my_txt_file") as f:
  lines = f.readlines()
result = [tuple(int(s) for s in line.strip().split(",")) for line in lines]

better, as Ilja Everilä pointed out, "open file as iterator": 就像IljaEverilä指出的那样,“打开文件作为迭代器”更好:

with open("my_txt_file") as f:
  result = [tuple(int(s) for s in line.strip().split(",")) for line in f]

Read all the content on the basis of new line from file. 从文件中换行读取所有内容。 Strip the newlines from each string. 从每个字符串中删除换行符。 Then convert each string into tuple by splitting on comma. 然后通过用逗号分割将每个字符串转换为元组。 Below is the code witha text file input having content as you have asked and result as you expected. 以下是带有文本文件输入的代码,其中包含您所要求的内容和预期的结果。

import sys
def test(filename):
    f = open(filename)
    lines = f.readlines()
    lines = [item.rstrip("\n") for item in lines]
    newList = list()
    for item in lines:
            item = item.split(",")
            item = tuple(int(items) for items in item)
            newList.append(item)                
    f.close()
    print newList

if __name__ == "__main__":
    test(sys.argv[1])

O/P:
techie@gateway2:myExperiments$ python test.py /export/home/techie/myExperiments/test.txt
[(68, 125), (113, 69), (65, 86), (108, 149), (152, 53), (78, 90), (54, 160), (20, 137), (107, 90), (48, 12)]

Hope this will help. 希望这会有所帮助。 :-) :-)

As your file contains comma separated integer values, you could use the csv module to handle it: 由于文件包含逗号分隔的整数值,因此可以使用csv模块来处理它:

import csv

with open(filename, newline='') as f:
    reader = csv.reader(f)
    numbers = [tuple(map(int, row)) for row in reader]

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

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