[英]How can I replace Unicode characters with Turkish characters in a text file with Python
我在推特上工作。 我使用 Stream API 從 Twitter 獲取數據,應用程序的結果是 JSON 文件。 我在文本文件中寫了推文數據,現在我看到了 Unicode 字符而不是土耳其語字符。 我不想在 Notepad++ 中手動查找/替換。 是否有任何自動選項可以通過打開 txt 文件、讀取文件中的所有數據並通過 Python 將 Unicode 字符更改為土耳其語字符來替換字符?
這是我要替換的 Unicode 字符和土耳其語字符。
我嘗試了兩種不同的類型
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
dosya = open('veri.txt', 'r')
for line in dosya:
match = re.search(line, "\u011f")
if (match):
replace("\u011f", "ğ")
dosya.close()
和:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
f1 = open('veri.txt', 'r')
f2 = open('veri2.txt', 'w')
for line in f1:
f2.write=(line.replace('\u011f', 'ğ'))
f2.write=(line.replace('\u011e', 'Ğ'))
f2.write=(line.replace('\u0131', 'ı'))
f2.write=(line.replace('\u0130', 'İ'))
f2.write=(line.replace('\u00f6', 'ö'))
f2.write=(line.replace('\u00d6', 'Ö'))
f2.write=(line.replace('\u00fc', 'ü'))
f2.write=(line.replace('\u00dc', 'Ü'))
f2.write=(line.replace('\u015f', 'ş'))
f2.write=(line.replace('\u015e', 'Ş'))
f2.write=(line.replace('\u00e7', 'ç'))
f2.write=(line.replace('\u00c7', 'Ç'))
f1.close()
f2.close()
這兩個都不起作用。 我怎樣才能讓它工作?
JSON 允許“轉義”和“非轉義”字符。 Twitter API 只返回轉義字符的原因是它可以使用 ASCII 編碼,這增加了互操作性。 對於土耳其語字符,您需要另一種編碼。 使用open
函數打開文件會打開一個假定您當前的語言環境編碼的文件,這可能是您的編輯器所期望的。 如果您希望輸出文件具有例如ISO-8859-9
編碼,您可以將encoding='ISO-8859-9
' 作為附加參數傳遞給open
函數。
您可以使用json.load
函數讀取包含 JSON 對象的文件。 這將返回一個帶有解碼轉義字符的 Python 對象。 使用json.dump
再次json.dump
並傳遞ensure_ascii=False
作為參數會將對象寫回文件而不將土耳其語字符編碼為轉義序列。 一個例子:
import json
inp = open('input.txt', 'r')
out = open('output.txt', 'w')
in_as_obj = json.load(inp)
json.dump(in_as_obj, out, ensure_ascii=False)
您的文件並不是真正的 JSON 文件,而是包含多個 JSON 對象的文件。 如果每個 JSON 對象都在自己的行上,您可以嘗試以下操作:
import json
inp = open('input.txt', 'r')
out = open('output.txt', 'w')
for line in inp:
if not line.strip():
out.write(line)
continue
in_as_obj = json.loads(line)
json.dump(in_as_obj, out, ensure_ascii=False)
out.write('\n')
但是在您的情況下,最好首先將未轉義的 JSON 寫入文件。 嘗試用(未經測試)替換你的on_data
方法:
def on_data(self, raw_data):
data = json.loads(raw_data)
print(json.dumps(data, ensure_ascii=False))
您可以使用此方法:
# For Turkish Character
translationTable = str.maketrans("ğĞıİöÖüÜşŞçÇ", "gGiIoOuUsScC")
yourText = "Pijamalı Hasta Yağız Şoföre Çabucak Güvendi"
yourText = yourText.translate(translationTable)
print(yourText)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.