tra*_*lad 257 python linux python-unicode
我有一个套接字服务器,应该从客户端接收UTF-8有效字符.
问题是一些客户端(主要是黑客)正在通过它发送所有错误的数据.
我可以很容易地区分真正的客户端,但我正在记录所有发送的数据文件,以便我以后可以分析它.
有时我会得到这样的字符œ
导致UnicodeDecodeError
错误.
我需要能够使用或不使用这些字符来生成字符串UTF-8.
更新:
对于我的特殊情况,套接字服务是一个MTA,因此我只希望接收ASCII命令,如:
EHLO example.com
MAIL FROM: <john.doe@example.com>
...
Run Code Online (Sandbox Code Playgroud)
我用JSON记录了所有这些.
然后一些没有良好意图的人决定出售各种垃圾.
这就是为什么对于我的特定情况,剥离非ASCII字符是完全可以的.
tra*_*lad 319
http://docs.python.org/howto/unicode.html#the-unicode-type
str = unicode(str, errors='replace')
Run Code Online (Sandbox Code Playgroud)
要么
str = unicode(str, errors='ignore')
Run Code Online (Sandbox Code Playgroud)
注意: 这将删除(忽略)有问题的字符,返回没有它们的字符串.
对我来说,这是理想的情况,因为我使用它作为非ASCII输入的保护,这是我的应用程序不允许的.
或者:使用codecs
模块中的open方法读入文件:
import codecs
with codecs.open(file_name, 'r', encoding='utf-8',
errors='ignore') as fdata:
Run Code Online (Sandbox Code Playgroud)
Doğ*_*ğuş 62
将引擎从C更改为Python对我来说是个窍门.
引擎是C:
pd.read_csv(gdp_path, sep='\t', engine='c')
Run Code Online (Sandbox Code Playgroud)
'utf-8'编解码器无法解码位置18中的字节0x92:无效的起始字节
引擎是Python:
pd.read_csv(gdp_path, sep='\t', engine='python')
Run Code Online (Sandbox Code Playgroud)
对我没有错误.
Jam*_*mac 55
现在我已经转移到Python 3,这种类型的问题突然出现了.我不知道Python 2只是简单地推动了文件编码的任何问题.
我找到了这个差异的很好的解释,以及如何找到解决方案,因为上述任何一个都没有.
http://python-notes.curiousefficiency.org/en/latest/python3/text_file_processing.html
简而言之,要使Python 3的行为与Python 2尽可能相似,请使用:
with open(filename, encoding="latin-1") as datafile:
# work on datafile here
Run Code Online (Sandbox Code Playgroud)
但是,阅读文章,没有一个适合所有解决方案.
Ign*_*ams 28
>>> '\x9c'.decode('cp1252')
u'\u0153'
>>> print '\x9c'.decode('cp1252')
œ
Run Code Online (Sandbox Code Playgroud)
mai*_*ter 19
我有同样的问题,UnicodeDecodeError
我用这条线解决了它.不知道是否是最好的方式,但它对我有用.
str = str.decode('unicode_escape').encode('utf-8')
Run Code Online (Sandbox Code Playgroud)
小智 9
此解决方案在使用拉丁美洲口音(例如“ñ”)时效果很好。
我只是通过添加解决了这个问题
df = pd.read_csv(fileName,encoding='latin1')
Run Code Online (Sandbox Code Playgroud)
首先,使用get_encoding_type来获取编码的文件类型:
import os
from chardet import detect
# get file encoding type
def get_encoding_type(file):
with open(file, 'rb') as f:
rawdata = f.read()
return detect(rawdata)['encoding']
Run Code Online (Sandbox Code Playgroud)
第二,打开以下类型的文件:
open(current_file, 'r', encoding = get_encoding_type, errors='ignore')
Run Code Online (Sandbox Code Playgroud)