从字符串中删除每个非utf-8符号

2024-05-15 07:34:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有很多文件和解析器。我要做的是去掉所有非utf-8符号并将数据放入mongodb。 目前我有这样的代码。

with open(fname, "r") as fp:
    for line in fp:
        line = line.strip()
        line = line.decode('utf-8', 'ignore')
        line = line.encode('utf-8', 'ignore')

不知怎的我还是犯了个错误

bson.errors.InvalidStringData: strings in documents must be valid UTF-8: 
1/b62010montecassianomcir\xe2\x86\x90ta0\xe2\x86\x90008923304320733/290066010401040101506055soccorin

我不明白。有什么简单的方法吗?

UPD:似乎Python和Mongo对Utf-8有效字符串的定义不太一致。


Tags: 文件数据代码in解析器mongodbwithline
3条回答

在代码行下面尝试,而不是最后两行。希望有帮助:

line=line.decode('utf-8','ignore').encode("utf-8")

不处理utf-8字符的示例

import string

test=u"\n\n\n\n\n\n\n\n\n\n\n\n\n\nHi <<First Name>>\nthis is filler text \xa325 more filler.\nadditilnal filler.\n\nyet more\xa0still more\xa0filler.\n\n\xa0\n\n\n\n\nmore\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfiller.\x03\n\t\t\t\t\t\t    almost there \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nthe end\n\n\n\n\n\n\n\n\n\n\n\n\n"

print ''.join(x for x in test if x in string.printable)

对于python 3,如本线程中的注释所述,您可以执行以下操作:

line = bytes(line, 'utf-8').decode('utf-8', 'ignore')

“ignore”参数防止在无法解码任何字符时引发错误。

如果您的行已经是bytes对象(例如b'my string'),那么您只需要使用decode('utf-8', 'ignore')对其进行解码。

相关问题 更多 >