![](/img/trans.png)
[英]Python3: print text with emojis read from text-file with non ASCII-characters (unicode_escape)
[英]Python How to print the text read from a file without the escape char?
python代碼是這樣的。 我嘗試從文件中讀取數據。 但是當我打印它時,我得到帶有square bracket
的輸出並escape char
。 如果僅打印從數據文件復制的內容。 正常顯示。 結果是這樣的: [u'\\n\\n\\xefhello']
如何解決此問題。 這是結果窗口。 我嘗試刪除square bracket
但是它不起作用。 而且我嘗試通過utf-8
編碼字符串,但均無法正常工作。
我從數據文件讀取的str <type 'unicode'>
是<type 'unicode'>
。
from bs4 import BeautifulSoup
import re
f = open('sgsres.txt', 'r')
content = f.read()
cleantext = BeautifulSoup(content, "lxml").text
cleantext = re.sub('[\[\]]', '', cleantext)
print cleantext
- 更新 -@鮑里斯
我根據您的回答重寫了代碼,但是我得到的輸出是這樣的。 在一行上輸出的每個字符和轉義字符似乎仍以原始文本形式打印出來。 20161212193059.bmp
- 更新 -
當我用acsii
編碼字符串並忽略這樣的錯誤時,此問題已解決。 text = text.encode('ascii',errors='ignore')
但我仍然不知道為什么。
Square brackets
表示您正在使用list
。
至於該list
內的string
,您可以執行以下操作:
from bs4 import BeautifulSoup
import re
f = open('sgsres.txt', 'r')
content = f.read()
cleantext = BeautifulSoup(content, "lxml").text
for item in cleantext:
item = item.strip()
print item
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.