I have a problem with transferring the dist parameter from the input file to the result file to the same place where it was located in the input file My code is:
import requests
import json
import time
with open("query4.txt", "rt") as file:
data_file = file.read()
with open("result.txt", "w") as f_o:
for line in data_file.split("\n"):
for i in range(1):
drX, drY, fromX, fromY, dist = line.split(",")
url = "https://api.openrouteservice.org/directions?"
params = [
["api_key", "my_api_key"],
["coordinates", "%s,%s|%s,%s" % (drY, drX, fromY, fromX)],
["profile", "driving-car"]
]
headers = {
"Accept": "application/json, application/geo+json,"
"application/gpx+xml, img/png; charset=utf-8"}
responce = requests.get(url=url, params=params, headers=headers)
print(responce.url)
# print(responce.text)
result = json.loads(responce.text)
print(result)
for rows in result["routes"]:
print(rows["summary"]["distance"], file=f_o) # depending on how do you want the result
# print(result["routes"])
time.sleep(0)
Input sample:
48.94205856,38.48511505,48.94167600,38.49207300,511
46.54586411,30.64417267,46.53338808,30.65455914,1599
50.06436157,31.44526100,50.07415641,31.45929694,1482
50.35911942,30.94097710,50.33576900,30.95166500,2706
50.35837936,30.94162369,50.33576900,30.95166500,2614
As the output now i have a distance from summary json like
123.2
122.5
221
312.7
212
I want to get this
123.2 125
122.5 122
221 340
312.7 300
212 220
I used this, but it seems not to work:
with open("query4.txt") as f:
input_file = f.read()
with open("result.txt", "w") as f1:
for line in input_file.split("\n"):
for line in f:
dX, dY, fX, fY, dst = line.split(",")
if "dst" in line:
f1.write(line)
You simply have to add the dist
variable to the print command. Also, there are a few improvements that could bring to your code:
import requests
import json
url = "https://api.openrouteservice.org/directions?"
headers = {"Accept": "application/json, application/geo+json, application/gpx+xml, img/png; charset=utf-8"}
with open("query4.txt", "rt") as f_i, open("result.txt", "w") as f_o:
for line in f_i:
drX, drY, fromX, fromY, file_dist = line.split(",")
params = [
["api_key", "my_api_key"],
["coordinates", "%s,%s|%s,%s" % (drY, drX, fromY, fromX)],
["profile", "driving-car"]
]
response = requests.get(url=url, params=params, headers=headers)
result = json.loads(response.text)
for rows in result["routes"]:
f_o.write("{from_api} - {from_file}\n".format(from_api = rows["summary"]["distance"], from_file = file_dist) )
If you wonder about the formatting part, take a look there: https://realpython.com/python-string-formatting
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.