[英]Python 3 and Unicode - How do I print newlines (general problems understanding this)
我已經篩選了很多關於python / unicode的解釋,但我似乎對此沒有任何意義。
情況如下:
我正在從reddit(制造機器人)中刪除評論的負載,並希望將它們主要存儲在MongoDB中,但是還需要能夠打印出評論樹,以便手動檢查正在發生的事情。
到目前為止,向數據庫中添加注釋沒有任何問題,但是當我嘗試打印輸出標准輸出時,CP1252字符集遇到了字符集的麻煩,顯然它不支持該字符集。
如我所讀,在Python 3中,所有內部內容(字符串)都以Unicode形式存儲,輸入和輸出必須為字節,因此這很好-我可以將Unicode編碼為CP1252,在幾種情況下,我會看到\\我不介意的x **個字符-我猜它們代表超出范圍的字符嗎?
問題是我正在使用\\ n(換行符)和制表符將注釋樹(輸出到stdout)打印出來,因此很容易查看,但是顯然,當您用換行符轉義序列對Unicode字符串進行編碼時,它會將它們轉義,從而將它們打印為文字。
供參考的是我的編碼語句:
encoded = post.tree_to_string().encode('cp1252','ignore')
謝謝
編輯:
我想要的是
|Parent Comment
|Child comment 1
|GChild comment 1
|Child comment 2
|Parent Comment 2
我得到的是
b"\n|Parent comment \n\n |Child comment \n\n etc
當打印到控制台時,Python會自動以控制台的編碼對字符串進行編碼(在美國Windows中為cp437
),並對控制台編碼不支持的任何字符引發異常。 例如:
#!python3
#coding: utf8
print('Some text\nwith Chinese 美國\ncp1252 ÀÁÂÃ\nand cp437 ░▒▓')
輸出:
Traceback (most recent call last):
File "C:\test.py", line 5, in <module>
print('Some text\nwith Chinese \u7f8e\u56fd\ncp1252 \xc0\xc1\xc2\xc3\nand cp437 ░▒▓')
File "C:\Python33\lib\encodings\cp437.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_map)[0]
UnicodeEncodeError: 'charmap' codec can't encode characters in position 24-25: character maps to <undefined>
要更改此默認值,您可以更改stdout
以顯式指定編碼以及如何處理錯誤:
#!python3
#coding: utf8
import io,sys
sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding=sys.stdout.encoding,errors='replace')
print('Some text\nwith Chinese 美國\ncp1252 ÀÁÂÃ\nand cp437 ░▒▓')
輸出(到cp437控制台):
Some text
with Chinese ??
cp1252 ????
and cp437 ░▒▓
您還可以通過直接寫入其buffer
接口來顯式地執行此操作,而無需更改stdout
:
sys.stdout.buffer.write('Some text\nwith Chinese 美國\ncp1252 ÀÁÂÃ\nand cp437 ░▒▓'.encode('cp437',errors='replace'))
第三種選擇是在啟動Python之前設置以下環境變量,這將更改stdout
類似於TextIOWrapper
解決方案:
PYTHONIOENCODING=cp437:replace
最后,由於您還提到了寫入文件,因此查看正在寫入的所有字符的最簡單方法是使用UTF-8作為文件的編碼:
#!python3
#coding: utf8
with open('out.txt','w',encoding='utf8') as f:
f.write('Some text\nwith Chinese 美國\ncp1252 ÀÁÂÃ\nand cp437 ░▒▓')
我不知道我是否正確理解了您的問題,但是您不能在打印到標准輸出之前只是刪除換行符和制表符嗎?
print(re.sub('[\t\n]', ' ', post.tree_to_string()))
你也可以告訴Python除去所有的控制字符,如表示在這里 。
在python3中打印時不需要編碼字符串到字節的編碼,只需將您的stdout(console)設置為unicode環境即可。
print(* objects,sep ='',end ='\\ n',file = sys.stdout,flush = False)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.