【问题标题】:Delete all files in directory with non utf-8 symbols删除目录中所有非 utf-8 符号的文件
【发布时间】:2012-11-06 12:24:11
【问题描述】:

我有一组数据,但我只需要使用utf-8 数据,所以我需要删除所有非utf-8 符号的数据。

当我尝试使用这些文件时,我收到:

UnicodeDecodeError: 'charmap' codec can't decode byte 0x8d in position 3062: character maps to <undefined> and UnicodeDecodeError: 'utf8' codec can't decode byte 0xc1 in position 1576: invalid start byte 

我的代码

class Corpus:
        def __init__(self,path_to_dir=None):
                self.path_to_dir = path_to_dir if path_to_dir else []


        def emails_as_string(self):
                for file_name in os.listdir(self.path_to_dir):
                        if not file_name.startswith("!"):
                                with io.open(self.add_slash(self.path_to_dir)+file_name,'r', encoding ='utf-8') as body:
                                        yield[file_name,body.read()]                        

        def add_slash(self, path):
                if path.endswith("/"): return path
                return path + "/"

我在yield[file_name,body.read()] 和这里list_of_emails = mailsrch.findall(text) 收到错误,但是当我使用 utf-8 时一切都很好。

【问题讨论】:

  • 所有 ASCII 字符都是 UTF-8 字符too.. 你的意思是“非 ASCII”吗?
  • 当我在我的程序中使用其他符号时,我会收到 UnicodeDecodeError: 'charmap' codec can't decode byte 0x8d in position 3062: character maps to &lt;undefined&gt;UnicodeDecodeError: 'utf8' codec can't decode byte 0xc1 in position 1576: invalid start byte
  • 能否也包含您的代码?

标签: python unicode python-3.x filenames


【解决方案1】:

我怀疑你想在bytes.decode 上使用errors='ignore' 参数。请参阅 http://docs.python.org/3/howto/unicode.html#unicode-howtohttp://docs.python.org/3/library/stdtypes.html#bytes.decode 了解更多信息。

编辑:

这里有一个例子展示了一个很好的方法:

for file_name in os.listdir(self.path_to_dir):
    if not file_name.startswith("!"):
        fullpath = os.path.join(self.path_to_dir, file_name)
        with open(fullpath, 'r', encoding ='utf-8', errors='ignore') as body:
            yield [file_name, body.read()]  

使用os.path.join,您可以消除您的add_slash 方法,并确保它可以跨平台工作。

【讨论】:

  • 所以我想像这样yield[file_name,body.read().decode("utf-8", "ignore")].decode("utf-8", "ignore") 添加到我的代码yield[file_name,body.read()] 中?顺便说一句,我仍然有错误UnicodeDecodeError: 'utf8' codec can't decode byte 0xc1 in position 1576: invalid start byte
  • 不,因为您使用的是io.open,所以您可以在其中使用errors 参数,例如io.open(filename, 'r', encoding='utf-8', errors='ignore')。顺便说一句,请注意,os.path.join 建立路径通常是一个好主意。我还建议改用内置的open。我将更新我的答案以显示这些示例。
猜你喜欢
  • 2016-07-25
  • 1970-01-01
  • 2014-12-19
  • 2011-04-04
  • 2015-05-12
  • 2020-06-01
  • 2016-08-18
  • 2011-12-04
  • 2018-12-27
相关资源
最近更新 更多