简体   繁体   English

在python中将字符串转换为unicode

[英]converting string to unicode in python

I am trying to convert a string type to Unicode in Python. 我试图在Python中将字符串类型转换为Unicode。 I want it to work for any non-english string, for example Japanese, Chinese or Spanish. 我希望它适用于任何非英语字符串,例如日语,中文或西班牙语。

For example, japanese_var has some japanese characters [ドキュメントを翻訳します]. 例如,japanese_var有一些日语字符[ドキュメントを翻訳します]。

Printing it would give, 打印它会给,

'\x83h\x83L\x83\x85\x83\x81\x83\x93\x83g\x82\xf0\x96|\x96\xf3\x82\xb5\x82\xdc\x82\xb7'

Checking its type, 检查其类型,

type(japanese_var)
<type 'str'>

How can I convert it to type 'unicode'? 如何将其转换为“ unicode”类型?

Should i use japanese_var.decode('mbcs')? 我应该使用japanese_var.decode('mbcs')吗? What could be the consequences of using this code as i will be using it on different OS platforms & different foreign Locale? 使用此代码可能会有什么后果,因为我将在不同的OS平台和不同的外部区域设置上使用它?

I am using python 2.5.4 我正在使用python 2.5.4

I am reading the parameter which can be any non-english string of a file from its properties. 我正在从其属性读取参数,该参数可以是文件的任何非英语字符串。

You need to know the encoding of the input string. 您需要知道输入字符串的编码。 There is no reliable universal solution. 没有可靠的通用解决方案。

The encoding should be available from the source of the input string. 编码应可从输入字符串的源中获得。 For instance, if you're taking text from a web page, the encoding should be indicated as part of the HTTP Content-Type , either as a HTTP response header from the server or as <meta> tag in the page source. 例如,如果您要从网页上获取文本,则应将编码表示为HTTP Content-Type ,作为服务器的HTTP响应标头或页面源中的<meta>标记。

Once you know the encoding, use the decode method. 知道编码后,请使用decode方法。

This string appears to be Shift-JIS: 该字符串似乎是Shift-JIS:

>>> x = '\x83h\x83L\x83\x85\x83\x81\x83\x93\x83g\x82\xf0\x96|\x96\xf3\x82\xb5\x82\xdc\x82\xb7'
>>> print x.decode( "shift-jis" )
ドキュメントを翻訳します

It worked for me by passing "mbcs" to decode for any locale. 它通过传递“ mbcs”来解码任何语言环境而对我有用。

Thanks guys for your help. 谢谢大家帮助。

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

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