简体   繁体   English

Python 帮助读取文本文件

[英]Python help reading from a text file

I have to make a program in python where i compute the distance using the latitude and longitude of numbers from a text file.我必须在 python 中制作一个程序,我使用文本文件中数字的纬度和经度来计算距离。 I know how to do the computations, but i am lost on how to match the latitude and long from the text file.我知道如何进行计算,但我不知道如何匹配文本文件中的纬度和长度。 my text file looks like this for instance:例如,我的文本文件如下所示:

38.898      -77.037
38.897      -77.043

I need to match the first number w/ lat1 and the bottom number w/ lat2.我需要匹配带有 lat1 的第一个数字和带有 lat2 的底部数字。 Thank you.谢谢你。

Just create a list of [longitude, latitude] values.只需创建一个[longitude, latitude]值列表。

import re

coordinates = []

with open('myfile.txt') as myfile:
     for line in myfile.readlines():
         coordinates.append(re.findall(r'[\d.]+', line))

Now you can easily fetch any value, and do your computation, like现在您可以轻松获取任何值,并进行计算,例如

lat1 = coordinates[0][1]
long2 = coordinates[1][0]

Assuming you have only two lines in the file:假设文件中只有两行:

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)

Output:输出:

38.898
-77.037
38.897
-77.043

You can easily generalize it using a for loop.您可以使用for循环轻松地概括它。

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)

output输出

['38.898', '77.037'] ['38.898','77.037']

['38.897', '77.043'] ['38.897','77.043']

['58.897', '77.045'] ['58.897','77.045']

['58.897', '77.045'] ['58.897','77.045']

['31.191', '77.037'] ['31.191','77.037']

['31.192', '77.043'] ['31.192','77.043']

['51.191', '77.049'] ['51.191','77.049']

['51.190', '77.045'] ['51.190','77.045']

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

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