简体   繁体   English

如何将python代码字符转换为人类可读代码

[英]How to convert python code character to human readable code

I am currently using Google Vision API in python to detect Chinese character in an image, but I found google will return python source code (Such as \\xe7\\x80\\x86\\xe7\\xab\\x91) instead of some human-readable string. 我目前在python中使用Google Vision API来检测图像中的汉字,但是我发现Google会返回python源代码(例如\\ xe7 \\ x80 \\ x86 \\ xe7 \\ xab \\ x91),而不是一些人类可读的字符串。

How can I convert it to human-readable text with utf-8 format? 如何将其转换为utf-8格式的可读文本?


Thanks all of your answer, may be I post my code is more easily for all of you. 感谢您的所有回答,也许我可以为所有人更轻松地发布我的代码。 Here is my code, basically I try to convert the whole json return from GOOGLE Vision and save in a json file, however, it hasn't success. 这是我的代码,基本上,我尝试将GOOGLE Vision的整个json返回值转换为一个json文件,但是并没有成功。

try: code = requests.post(' https://vision.googleapis.com/v1/images:annotate?key= '+GOOGLE_API_KEY, data=params,headers=headers) 试试:代码= request.post(' https://vision.googleapis.com/v1/images:annotate?key='+ GOOGLE_API_KEY,data = params,headers = headers)

resultText = code.text.encode("utf-8")
outputFileName = image_path.split('.',1)[0]
outputDataFile = open(outputFileName+".json", "w")
outputDataFile.write(json.dumps(resultText))
outputDataFile.close()

except requests.exceptions.ConnectionError: print('Request error') 除了request.exceptions.ConnectionError:print('请求错误')

Thank you 谢谢

t = '\xe7\x80\x86\xe7\xab\x91'
t = unicode('\xe7\x80\x86\xe7\xab\x91', 'utf8')
# Output: 瀆竑

More detailed information about Unicode in here . 有关Unicode的更多详细信息,请参见此处

I finally solve this by using the below code. 我终于使用以下代码解决了这个问题。 Thanks all of you 谢谢大家

try: code = requests.post(' https://vision.googleapis.com/v1/images:annotate?key= '+GOOGLE_API_KEY, data=params,headers=headers) resultText = json.loads(code.text) outputFileName = image_path.split('.',1)[0] with open(outputFileName+".json", "w", encoding='utf8') as f: json.dump(resultText, f, ensure_ascii=False,indent=4) f.close() except requests.exceptions.ConnectionError: print('Request error') 尝试:代码= request.post(' https://vision.googleapis.com/v1/images:annotate?key='+ GOOGLE_API_KEY,data = params,headers = headers)resultText = json.loads(code.text)outputFileName = image_path.split('。',1)[0],其中open(outputFileName +“。json”,“ w”,encoding ='utf8')为f:json.dump(resultText,f,sure_ascii = False,indent = 4)f.close()除外request.exceptions.ConnectionError:print('请求错误')

I assume you mean you have a literal string like \\xe4\\xb8\\x89 and you want to convert this into the character . 我假设您的意思是您有一个文字字符串,例如\\xe4\\xb8\\x89并且您想将其转换为字符

It's very strange that there isn't a straightforward way to do this. 没有一个简单的方法可以做到这一点,这很奇怪。 The best i can come up with is: 我能想到的最好的是:

s = '\\xe4\\xb8\\x89'
print(bytes.fromhex(s.replace('\\x', '')).decode('utf-8')) # prints 三

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM