用一个空格替换非 ASCII 字符
- 2025-01-08 08:50:00
- admin 原创
- 85
问题描述:
我需要将所有非 ASCII ( -) 字符替换为空格。我很惊讶这在 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 字符?
在 无数 类似的SO问题中,没有一个问题解决字符替换而不是剥离,并且另外 解决所有非ASCII字符而不是特定字符。
解决方案 1:
您的''.join()
表达式正在过滤,删除任何非 ASCII 内容;您可以改用条件表达式:
return ''.join([i if ord(i) < 128 else ' ' for i in text])
这将逐个处理字符,并且每个替换的字符仍将使用一个空格。
你的正则表达式应该用空格替换连续的非 ASCII 字符:
re.sub(r'[^x00-x7F]+',' ', text)
注意+
那里。
解决方案 2:
为了让您获得与原始字符串最相似的表示,我推荐使用unidecode 模块:
Python 2
from unidecode import unidecode
def remove_non_ascii(text):
return unidecode(unicode(text, encoding = "utf-8"))
然后你可以在字符串中使用它:
remove_non_ascii("Ceñía")
Cenia
Python 3
from unidecode import unidecode
unidecode("Ceñía")
解决方案 3:
对于字符处理,使用 Unicode 字符串:
PythonWin 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 10:57:17) [MSC v.1600 64 bit (AMD64)] on win32.
>>> s='ABC马克def'
>>> import re
>>> re.sub(r'[^x00-x7f]',r' ',s) # Each char is a Unicode codepoint.
'ABC def'
>>> b = s.encode('utf8')
>>> re.sub(rb'[^x00-x7f]',rb' ',b) # Each char is a 3-byte UTF-8 sequence.
b'ABC def'
但请注意,如果您的字符串包含分解的 Unicode 字符(例如,单独的字符和组合重音符号),您仍然会遇到问题:
>>> s = 'mañana'
>>> len(s)
6
>>> import unicodedata as ud
>>> n=ud.normalize('NFD',s)
>>> n
'mañana'
>>> len(n)
7
>>> re.sub(r'[^x00-x7f]',r' ',s) # single codepoint
'ma ana'
>>> re.sub(r'[^x00-x7f]',r' ',n) # only combining mark replaced
'man ana'
解决方案 4:
如果替换字符可以是“?”而不是空格,那么我建议result = text.encode('ascii', 'replace').decode()
:
"""Test the performance of different non-ASCII replacement methods."""
import re
from timeit import timeit
# 10_000 is typical in the project that I'm working on and most of the text
# is going to be non-ASCII.
text = 'Æ' * 10_000
print(timeit(
"""
result = ''.join([c if ord(c) < 128 else '?' for c in text])
""",
number=1000,
globals=globals(),
))
print(timeit(
"""
result = text.encode('ascii', 'replace').decode()
""",
number=1000,
globals=globals(),
))
结果:
0.7208260721400134
0.009975979187503592
解决方案 5:
这个怎么样?
def replace_trash(unicode_string):
for i in range(0, len(unicode_string)):
try:
unicode_string[i].encode("ascii")
except:
#means it's non-ASCII
unicode_string=unicode_string[i].replace(" ") #replacing it with a single space
return unicode_string
解决方案 6:
作为一种原生且高效的方法,您无需使用ord
或对字符进行任何循环。只需使用编码ascii
并忽略错误即可。
下面的操作只会删除非 ASCII 字符:
new_string = old_string.encode('ascii',errors='ignore')
现在如果您想替换已删除的字符,只需执行以下操作:
final_string = new_string + b' ' * (len(old_string) - len(new_string))
解决方案 7:
当我们使用时ascii()
,它会转义非 ASCII 字符,并且无法正确更改 ASCII 字符。所以我的主要想法是,它不会更改 ASCII 字符,因此我会遍历字符串并检查字符是否已更改。如果已更改,则用替换器替换它,即您给出的内容。
例如:' '(单个空格)或 '?'(带问号)。
def remove(x, replacer):
for i in x:
if f"'{i}'" == ascii(i):
pass
else:
x=x.replace(i,replacer)
return x
remove('hái',' ')
结果:“h i”(中间有一个空格)。
语法: remove(str,non_ascii_replacer)
str = 在这里您将提供您想要使用的字符串。non_ascii_replacer
= 在这里您将提供您想要用来替换所有非 ASCII 字符的替换器。
解决方案 8:
使用Raku(以前称为 Perl_6)进行预处理
~$ raku -pe 's:g/ <:!ASCII>+ / /;' file
示例输入:
Peace be upon you
السلام عليكم
שלום עליכם
Paz sobre vosotros
示例输出:
Peace be upon you
Paz sobre vosotros
请注意,您可以使用以下代码获取有关比赛的详细信息:
~$ raku -ne 'say s:g/ <:!ASCII>+ / /.raku;' file
$( )
$(Match.new(:orig("السلام عليكم"), :from(0), :pos(6)), Match.new(:orig("السلام عليكم"), :from(7), :pos(12)))
$(Match.new(:orig("שלום עליכם"), :from(0), :pos(4)), Match.new(:orig("שלום עליכם"), :from(5), :pos(10)))
$( )
$( )
或者更简单地说,你可以直观地看到替换的空白处:
~$ raku -ne 'say S:g/ <:!ASCII>+ / /.raku;' file
"Peace be upon you"
" "
" "
"Paz sobre vosotros"
""
https://docs.raku.org/language/regexes#Unicode_properties
https://www.codesections.com/blog/raku-unicode/
解决方案 9:
def filterSpecialChars(strInput):
result = []
for character in strInput:
ordVal = ord(character)
if ordVal < 0 or ordVal > 127:
result.append(' ')
else:
result.append(character)
return ''.join(result)
像这样调用它:
result = filterSpecialChars('Ceñía mañana')
print(result)
解决方案 10:
我的问题是,我的字符串包含诸如BelgiÃ
België 和€
€ 符号之类的内容。我不想用空格替换它们。而是用正确的符号本身。
我的解决方案是 string.encode('Latin1').decode('utf-8')
解决方案 11:
可能针对不同的问题,但我提供 @Alvero 答案的我的版本(使用 unidecode)。我想对我的字符串进行“常规”剥离,即我的字符串的开头和结尾为空格字符,然后仅用“常规”空格替换其他空格字符,即
"Ceñíaㅤmañanaㅤㅤㅤㅤ"
到
"Ceñía mañana"
,
def safely_stripped(s: str):
return ' '.join(
stripped for stripped in
(bit.strip() for bit in
''.join((c if unidecode(c) else ' ') for c in s).strip().split())
if stripped)
我们首先用常规空格替换所有非 Unicode 空格(然后再将其重新连接回来),
''.join((c if unidecode(c) else ' ') for c in s)
然后我们再次进行拆分,使用 Python 的常规拆分方法,剥离每个“位”,
(bit.strip() for bit in s.split())
最后再将它们连接起来,但前提是字符串通过了测试if
,
' '.join(stripped for stripped in s if stripped)
这样,就safely_stripped('ㅤㅤㅤㅤCeñíaㅤmañanaㅤㅤㅤㅤ')
可以正确返回'Ceñía mañana'
。
解决方案 12:
用空格替换所有非 ASCII( -)字符:
''.join(map(lambda x: x if ord(x) in range(0, 128) else ' ', text))
要替换所有可见字符,请尝试以下操作:
import string
''.join(map(lambda x: x if x in string.printable and x not in string.whitespace else ' ', text))
这将产生相同的结果:
''.join(map(lambda x: x if ord(x) in range(32, 128) else ' ', text))