用Python从文本文件中检索坐标
我有一个带有坐标的文本文件,其格式如下:用Python从文本文件中检索坐标,python,coordinates,Python,Coordinates,我有一个带有坐标的文本文件,其格式如下: 158,227,,396,226,,487,138,,473,48,,145,55,,139,133,,159,229 413,289,,547,156,,526,26,,140,10,,85,147,,115,245,,415,291 295,175,,292,293 import re with open('test.txt') as f: for line in f: line.strip() line =
158,227,,396,226,,487,138,,473,48,,145,55,,139,133,,159,229
413,289,,547,156,,526,26,,140,10,,85,147,,115,245,,415,291
295,175,,292,293
import re
with open('test.txt') as f:
for line in f:
line.strip()
line = re.sub(r',,', ' ', line)
print line
158,227 396,226 487,138 473,48 145,55 139,133 159,229
413,289 547,156 526,26 140,10 85,147 115,245 415,291
295,175 292,293
使用strip an re.sub,我得到如下结果:
158,227,,396,226,,487,138,,473,48,,145,55,,139,133,,159,229
413,289,,547,156,,526,26,,140,10,,85,147,,115,245,,415,291
295,175,,292,293
import re
with open('test.txt') as f:
for line in f:
line.strip()
line = re.sub(r',,', ' ', line)
print line
158,227 396,226 487,138 473,48 145,55 139,133 159,229
413,289 547,156 526,26 140,10 85,147 115,245 415,291
295,175 292,293
我想使用那些坐标对
(x,y)
,但我不知道怎么做。您的字符串替换无法帮助您从中获取数字。老实说,这会使事情复杂化
这里最直观的方法肯定是:
,
with open('test.txt') as f:
for line in f:
items = line.split()
现在,让我们把坐标组合成元组。我们只关心第一和第二个坐标,然后向前跳三个,以此类推。这就是[start:stop:step]
语法的作用zip
获取多个iterables,并将它们组合成元组(按元素)
tuples_of_strings = zip(coordinates[0::3], coordinates[1::3])
然后,您可能希望生成该点的点(x,y)
对象
points = [Point(float(tup[0]), float(tup[1])) for tup in tuples_of_strings]
在这种情况下为什么需要正则表达式
>>> with open('file') as f:
... t = f.read().replace('\n', ',,')
>>> [[int(j) for j in i.split(',')] for i in t.split(',,') if i]
[[158, 227],
[396, 226],
[487, 138],
[473, 48],
[145, 55],
[139, 133],
[159, 229],
[413, 289],
[547, 156],
[526, 26],
[140, 10],
[85, 147],
[115, 245],
[415, 291],
[295, 175],
[292, 293]]
您想如何使用它们?你没告诉我们,对不起,我说得不够具体。我想用x和y坐标画一个点,像这样:点(x,y)谢谢!这帮我完成了任务。