我清理了字典的一些鍵并嘗試將它們添加到新字典中,所以我只能使用它們。但是,當我嘗試對 Radaufh?¤ngung 或 Z??ndanlage 等密鑰進行編碼和解碼并將它們添加到新的 dict 中時,我得到了一個錯誤。我的問題是是否有辦法解決這個問題,或者是否有更好的解決方案來處理這個問題(第 49 行)?
我的代碼:
import requests
import json
import time
from requests.exceptions import HTTPError
attempts = 0
def get_data_from_url(url):
try:
response = requests.get(url)
# If the response was successful, no Exception will be raised
response.raise_for_status()
except HTTPError:
return "HTTPError"
else:
response_dict = json.loads(response.text)
return response_dict
url = get_data_from_url("http://160.85.252.148/")
#(1) upon no/invalid response, the query is resubmitted with exponential backoff waiting time in between requests to avoid server overload;
while url == "HTTPError":
attempts = 1
time.sleep(attempts * 1.5)
url = get_data_from_url("http://160.85.252.148/")
print(url)
#(2) material records with missing or invalid cost are ignored;
valid_values = {}
for key in url:
if type(url[key]) == int or type(url[key]) == float and url[key].isdigit() == True:
#(3) wrongly encoded umlauts are repaired.
key = key.encode('latin1').decode('utf8')
#key = key.replace('é', 'Oe').replace('?', 'ae').replace('ü', 'ue')
valid_values[key]=abs(url[key])
print(valid_values)
uj5u.com熱心網友回復:
您正在嘗試使用修改后的鍵訪問字典。存盤原始密鑰并在訪問字典時使用它:
okey = key
key = key.encode('latin1').decode('utf8')
...
valid_values[key]=abs(url[okey])
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/456025.html
