[英]How can pathlib read_text() method display German Umlaute correctly on Windows 10 Enterprise?
[英]Pathlib read_text as a string literal
我正在嘗試從 txt 文件中生成一些 json 數據。
txt 文件是從書籍中生成的,使用它們的 ocr,這使得它們無法估量(我不能隨機更改我不喜歡的字符,因為它們可能很重要)並且不可靠(ocr 可能出錯了,作者可以插入了會弄亂我的代碼的符號)。
截至目前,我有這個:
output_folder = Path(output_folder)
value = json.loads('{"nome": "' + file_name[:len(file_name)-4] + '", "testu": "' + (Path(filename).read_text()) + '"}')
path = output_folder / (file_name[:len(file_name)-4] + "_opare.json")
with path.open(mode="w+") as working_file:
working_file.write("[" + str(value) + "]")
working_file.close()
這向我拋出了錯誤json.decoder.JSONDecodeError: Invalid control character
是由我的書以 ' (引號)開頭(是)引起的。
我讀過關於字符串文字的內容,這似乎與我的情況有關,但我不知道如何使用它們。
我能做些什么?
謝謝
你為什么要做一個 json 只是為了再次解析它? 你可以只創建一個字典:
value = {
"nome": file_name[:len(file_name)-4],
"testu":Path(filename).read_text(),
}
從字里行間看, JSONDecodeError
實際上並不是來自這段代碼,是嗎? 它來自稍后讀取文件的代碼。
您不能使用str(value)
將 dict 寫入 JSON 文件。 Python 的 dict 到字符串的轉換使用單引號,這在 JSON 中是不合法的。 您需要將其轉換回 JSON:
with path.open(mode="w+") as working_file:
json.dump( [value], working_file )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.