python - 用一个空格替换非 ASCII 字符

标签 python unicode encoding ascii

我需要用空格替换所有非 ASCII (\x00-\x7F) 字符。我很惊讶这在 Python 中并不容易,除非我遗漏了一些东西。以下函数简单地删除所有非 ASCII 字符:

def remove_non_ascii_1(text):

    return ''.join(i for i in text if ord(i)<128)

并且这个根据字符代码点中的字节数将非ASCII字符替换为空格数(即-字符替换为3个空格):

def remove_non_ascii_2(text):

    return re.sub(r'[^\x00-\x7F]',' ', text)

如何用一个空格替换所有非 ASCII 字符?

Of the myriad of similar SO questions , none address character replacement as opposed to stripping , and 另外解决所有非ASCII字符而不是特定字符。

最佳答案

你的 ''.join() 表达式是过滤,删除任何非ASCII;您可以改用条件表达式:

return ''.join([i if ord(i) < 128 else ' ' for i in text])

这会逐个处理字符,并且每个替换字符仍会使用一个空格。

您的正则表达式应该只用空格替换 连续 个非 ASCII 字符:

re.sub(r'[^\x00-\x7F]+',' ', text)

注意那里的+

关于python - 用一个空格替换非 ASCII 字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20078816/

相关文章:

windows - 如何在Windows 10中的perl> = 5.18中强制为输出文件设置代码集cp1252?

python - Numpy 内存不足

python - 像 Labview 一样,在 python 中仅打开部分大型 TDMS 文件

python - Powershell - 现在提取传递给脚本的变量名称

在 IE6 中以不同大小呈现的 Unicode 字符

c++ - 在 iPhone 上使用 C++ 中的 Unicode 的最佳方式是什么?

python - Unicode 字符串的 lxml.etree.XML ValueError

python - Elif 语句显示我何时不希望它出现

c# - 这是什么编码 : <ESC>[00p<ESC>(1*259*01/26/10*11. 05*<CR>

encoding - Jasper 报告 PDF 编码