我必须在python中创建一个程序,我使用文本文件中数字的纬度和经度来计算距离。我知道如何进行计算,但我迷失了如何匹配文本文件中的纬度和长度。 我的文本文件如下所示:
38.898 -77.037
38.897 -77.043
我需要匹配第一个数字w / lat1和底部数字w / lat2。 谢谢。
答案 0 :(得分:0)
只需创建[longitude, latitude]
值列表。
import re
coordinates = []
with open('myfile.txt') as myfile:
for line in myfile.readlines():
coordinates.append(re.findall(r'[\d.]+', line))
现在您可以轻松获取任何值,并进行计算,例如
lat1 = coordinates[0][1]
long2 = coordinates[1][0]
答案 1 :(得分:0)
假设文件中只有两行:
convert = lambda line: map(float, line.strip().split())
with open('a.txt') as f:
lat1, long1 = convert( f.readline() )
lat2, long2 = convert( f.readline() )
print(lat1)
print(long1)
print(lat2)
print(long2)
38.898
-77.037
38.897
-77.043
您可以使用for
循环轻松概括它。
答案 2 :(得分:0)
38.898 -77.037
38.897 -77.043
58.897 -77.045
58.897 -77.045
31.191 -77.037
31.192 -77.043
51.191 -77.049
51.190 -77.045
import re
allNums = []
with open("dir", "r") as f:
for line in f:
l = re.findall('\d+.\d+',line)
if len(l) == 2:
allNums.extend(l)
# split list into size 2 sublists
coord = [allNums[i:i+2] for i in range(0, len(allNums), 2)]
for el in coord:
print(el)
<强>输出强>
[&#39; 38.898&#39;,&#39; 77.037&#39;]
[&#39; 38.897&#39;,&#39; 77.043&#39;]
[&#39; 58.897&#39;,&#39; 77.045&#39;]
[&#39; 58.897&#39;,&#39; 77.045&#39;]
[&#39; 31.191&#39;,&#39; 77.037&#39;]
[&#39; 31.192&#39;,&#39; 77.043&#39;]
[&#39; 51.191&#39;,&#39; 77.049&#39;]
[&#39; 51.190&#39;,&#39; 77.045&#39;]