문자열 사전이있는 파일을 사전 목록으로 변환하려고합니다. 파일은 https://github.com/szczor/sharing/blob/master/data.txt 에서 찾을 수 있습니다 . 시도하는 방법은 다음과 같습니다.
lista = []
with open(os.path.join(path_to_data, 'data.txt')) as filehandle:
for line in filehandle:
# remove linebreak which is the last character of the string
currentPlace = line[:-1]
# add item to the list
lista.append(currentPlace)
그래서 이제 문자열 인 요소가있는 목록이 있습니다.
print(type(lista[0]))
이제 해당 문자열을 사전으로 변환하려고
lista = [json.loads(str(string.replace('\'','\"'))) for string in lista]
하지만 오류가 발생합니다.
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
수동으로 만든 목록으로 동일한 방법을 시도했지만 모든 것이 작동했지만 왜 내 txt 파일에서 작동하지 않는지 모르겠습니다.
ast.literal_eval
이를 위해 사용할 수 있습니다 .
import ast
with open(os.path.join(path_to_data, 'data.txt')) as fp:
lines = fp.readlines()
# if there are irregularities, use a try/except to pass these (note, you may wish to use a logger in practice)
output = []
for line in lines:
try:
output.append(ast.literal_eval(line))
except ValueError:
print("malformed string; skipping this line")
except SyntaxError:
print("looks like some encoding errors with this file...")
산출:
[{'Lines': '130',
'Lon': 21.0082356,
'VehicleNumber': '1000',
'Time': '2020-12-23 14:19:31',
'Lat': 52.207217,
'Brigade': '2'},
{'Lines': '213',
'Lon': 21.1013111,
'VehicleNumber': '1001',
'Time': '2020-12-23 15:40:37',
'Lat': 52.2230756,
'Brigade': '2'},
{'Lines': '130',
'Lon': 21.003573,
'VehicleNumber': '1002',
'Time': '2020-12-23 15:40:39',
'Lat': 52.2060591,
'Brigade': '1'},
{'Lines': '311',
'Lon': 21.0807406,
'VehicleNumber': '1003',
'Time': '2020-12-23 15:40:35',
'Lat': 52.2414656,
'Brigade': '2'},
{'Lines': '213',
'Lon': 21.1746171,
'VehicleNumber': '1004',
'Time': '2020-12-23 15:40:24',
'Lat': 52.186474,
'Brigade': '3'},...
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다