본질적으로 내가 작성한 줄에서 특정 항목이있는 목록을 만들 수있는 스크립트를 만들려고합니다. SQL DB에 삽입 할 수 있습니다. 나는 텍스트 파일 "addresses.txt"에 다음과 같은 여러 개의 전화 회선이 : 예를 들어파일의 각 줄에서 여러 단어와 해당 값을 식별하는 방법 ex : "status": "ok"
{"status":"OK","message":"OK","data":[{"type":"addressAccessType","addressAccessId":"0a3f508f-e7c8-32b8-e044-0003ba298018","municipalityCode":"0766","municipalityName":"Hedensted","streetCode":"0072","streetName":"Værnegården","streetBuildingIdentifier":"13","mailDeliverySublocationIdentifier":"","districtSubDivisionIdentifier":"","postCodeIdentifier":"8000","districtName":"Århus","presentationString":"Værnegården 13, 8000 Århus","addressSpecificCount":1,"validCoordinates":true,"geometryWkt":"POINT(553564 6179299)","x":553564,"y":6179299}]}
내가
"type":"addressAccessType","addressAccessId":"0a3f508f-e7c8-32b8-e044-0003ba298018"
을 제거 할 그리고 열 목록과 함께 마지막까지하고 값 목록에 그이 같은 file_output.txt에 기록 될 수있다 :
INSERT INTO ADDRESSES (%s) VALUES (%s)
이것은 내가 지금까지 무엇을 가지고
# Writes %s into the file output_data.txt
address_line = """INSERT INTO ADDRESSES (%s) VALUES (%s)"""
# Reads every line from the file messy_data.txt
messy_string = file("addresses.txt").readlines()
cols = messy_string[0].split(",") #Defines each word in the first line separated by , as a column name
colstr = ','.join(cols) # formatted string that will plug in nicely
output_data = file("output_data.txt", 'w') # Creates the output file: output_data.txt
for r in messy_string[0:]: # loop through everything after first line
#r = r.replace(':',',')
#temp_replace = r.translate(None,'"{}[]()')
#address_list = temp_replace.split(",")
#address_list = [x.encode('utf-8') for x in address_list]
vals = r.split(",") # split at ,
valstr = ','.join(vals) # join with commas for sql
output_data.write(address_line % (colstr, valstr)) # write to file
output_data.close()
내 의견을 언급 한 일부 내용이 포함되어 있다면 어쩌면 도움이 될 수 있습니다. 또한 나는 항상 #address_list = temp_replace.split(",")
을 사용할 때 utf-8 문자는 모두 엉망이며, 왜 또는 어떻게 수정해야하는지 알지 못합니다. 나는 내 문제를 해결하기 위해이 코드와 함께 올라와있다 How can I convert JSON to CSV? 이 예를 보면
UPDATE :
# Reads every line from the file coordinates.txt
messy_string = file("coordinates.txt").readlines()
# Reads with the json module
x = json.loads(messy_string
x = json.loads(x)
f = csv.writer(open('test.csv', 'wb+'))
for x in x:
f.writerow([x['status'],
x['message'],
x['data']['type'],
x['data']['addressAccessId'],
x['data']['municipalityCode'],
x['data']['municipalityName'],
x['data']['streetCode'],
x['data']['streetName'],
x['data']['streetBuildingIdentifier'],
x['data']['mailDeliverySublocationIdentifier'],
x['data']['districtSubDivisionIdentifier'],
x['data']['postCodeIdentifier'],
x['data']['districtName'],
x['data']['presentationString'],
x['data']['addressSpecificCount'],
x['data']['validCoordinates'],
x['data']['geometryWkt'],
x['data']['x'],
x['data']['y']])
그러나,이 내 문제가 해결되지, 지금 나는 다음과 같은 오류가 발생합니다
Traceback (most recent call last):
File "test2.py", line 10, in <module>
x = json.loads(messy_string)
File "C:\Python27\lib\json\__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "C:\Python27\lib\json\decoder.py", line 365, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
TypeError: expected string or buffer
아무도 도와 줄 수 있습니까? 미리 감사드립니다.
감사합니다. Kartik. 나는 당신의 솔루션을 시도하고, Im 얻는 SyntaxError : 잘못된 구문을 출력 파일에 column_values 쓸 때 clean_data.write (address_line % (column_values)) 아직 모든 정교는 매우 고맙습니다. . – Philip
'column_values'는 문자열'% s'리스트입니다. 'print "% s"% ','. join (column_values)' – Kartik
답해 주셔서 감사합니다. 나는 단지 지난 주에 파이썬을 배우기 시작했고, 당신이 내가 인쇄를하고 싶은 곳을 확실히 모르겠다. 또한 다음과 같은 오류가 발생합니다 : _ "TypeError 예외는 구식 클래스 여야하거나 BaseException이 아닌 str에서 파생되었습니다."_ json 텍스트를 csv 텍스트로 열과 함께 변환 할 수있는 스크립트를 만들려고합니다. 내가 선택한 좀 더 정교하고 가능하면 조각을 연결할 수 있을까요? 미리 감사드립니다. – Philip