pycharm的console顯示亂碼和中文的配置

第一種方式:html

在python腳本開始的地方加入指定編碼方式python

# -*- coding : UTF-8 -*-bash

第二種方式:app

有些時候咱們會獲得這種格式的字符串:this

 "name": "\u6843\u674e\u9999\u677e\u86cb\u7cd5"編碼

可是在python console中若是輸入,則會這樣:spa

>>>a = "\u6843\u674e\u9999\u677e\u86cb\u7cd5"
>>>a
>>>'桃李香鬆蛋糕'
>>>type(a)
>>><class 'str'>code

貌似不用轉編碼就是中文啊,可是爲何仍是非中文呢,因此就須要以下的轉換:htm

若是type(text) is bytes,那麼
text.decode('unicode_escape')utf-8

若是type(text) is str,那麼
text.encode('latin-1').decode('unicode_escape')

 

第三種方式:

console中文顯示亂碼問題:

在settings->File encoding界面選擇
IDE Encodingproject Encoding(推薦都設置成utf-8)
不過這個設置貌似和程序的編碼有關,鑑於通常都是萬國碼。因此仍是這樣方便點。

 

第四種方式:

console中顯示unicode編碼,設置成顯示成中文:

Configuring Output Encoding

PyCharm creates files using the IDE encoding defined in the File Encodings page of the Settings dialog, which can be either system default, or the one selected from list of available encodings. Output in the consoles is also treated in this encoding.

It is possible that encoding used in the console output is different from the IDE default. To have PyCharm properly parse text in the console, you have to do some additional editing.

To set up encoding for the console output, depending on your operating system:

    • In Windows and Linux:

      Open for editing PYCHARM_HOME/bin/pycharm.exe.vmoptions
      or
      PYCHARM_HOME/bin/pycharm.vmoptions

      respectively, and add the following line at the bottom:
      -Dconsole.encoding=<encoding name>

      For example:
      -Dconsole.encoding=UTF-8

In macOS: Open Info.plist located in /應用程序/PyCharm/Contents/, locate the tag <key>VMOptions</key>, and modify it as follows:

<key>VMOptions</key> <string>-Xms16m -Xmx512m -XX:MaxPermSize=120m -Xbootclasspath/p:../lib/boot.jar -ea -Dconsole.encoding=<encoding name> </string>
沒有-Dconsole.encoding=<encoding name>,須要在文本中添加這部份內容,並將encoding name更改爲UTF-8
保存之後,重啓pycharm生效
 
Terminal終端執行python腳本,包含中文編碼報錯問題:
1.報錯信息
SyntaxError: Non-ASCII character '\xe4' in file sendredpicket.py on line 20, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details
 
處理方式: 將# -*- coding : UTF-8 -*- 或# -*- coding : utf-8 -*- 放到文本的第一行
 
2.報錯信息
 

UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)

 

處理方式:將對對應的中文進行一次utf-8編碼

text = u'你是好樣的'text = text.encode('utf-8')
相關文章
相關標籤/搜索