[英]Transfer text from one file to another
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: 我将dist参数从输入文件传输到结果文件到输入文件所在的相同位置时遇到问题,我的代码是:
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 作为输出,现在我与汇总json等有一段距离
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. 您只需要将dist
变量添加到print命令。 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 如果您想了解格式化部分,请看一下: https : //realpython.com/python-string-formatting
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.