想要解析文本并仅返回字母,数字,正斜杠和反斜杠,并用''替换所有其他斜杠。
是否可以仅使用一种正则表达式模式,而不是随后需要循环的几种正则表达式模式? 无法获取下面的样式,不能替换正斜杠。
line1 ="1/R~e`p!l@@a#c$e%% ^A&l*l( S)-p_e+c=ial C{har}act[er]s ;E xce|pt Forw:ard" $An>d B,?a..ck Sl'as
line2 = line
RGX_PATTERN ="[^\w]","_"
for pattern in RGX_PATTERN:
line = re.sub(r"%s" %pattern, '', line)
print("replace1:" + line)
#Prints: 1ReplaceAllSpecialCharactersExceptForwardAndBackSlashes2
以下来自SO的代码已经过测试,发现比regex更快,但随后它替换了所有要保留的特殊字符,包括/和。 有什么方法可以对其进行编辑以使其适合我的用例,并且仍然保持它在正则表达式方面的优势?
line2 = ''.join(e for e in line2 if e.isalnum())
print("replace2:" + line2)
#Prints: 1ReplaceAllSpecialCharactersExceptForwardAndBackSlashes2
作为一个额外的障碍,要解析的文本应采用ASCII格式,因此,如有可能,其他编码中的字符也应替换为''
更快一点并且适用于Unicode:
full_pattern = re.compile('[^a-zA-Z0-9\\\/]|_')
def re_replace(string):
return re.sub(full_pattern, '', string)
如果您真的想要它,那是迄今为止最好的方法(但有点晦涩):
def wanted(character):
return character.isalnum() or character in '\\/'
ascii_characters = [chr(ordinal) for ordinal in range(128)]
ascii_code_point_filter = [c if wanted(c) else None for c in ascii_characters]
def fast_replace(string):
# Remove all non-ASCII characters. Heavily optimised.
string = string.encode('ascii', errors='ignore').decode('ascii')
# Remove unwanted ASCII characters
return string.translate(ascii_code_point_filter)
时序:
SETUP="
busy = ''.join(chr(i) for i in range(512))
import re
full_pattern = re.compile('[^a-zA-Z0-9\\\/]|_')
def in_whitelist(character):
return character.isalnum() or character in '\\/'
def re_replace(string):
return re.sub(full_pattern, '', string)
def wanted(character):
return character.isalnum() or character in '\\/'
ascii_characters = [chr(ordinal) for ordinal in range(128)]
ascii_code_point_filter = [c if wanted(c) else None for c in ascii_characters]
def fast_replace(string):
string = string.encode('ascii', errors='ignore').decode('ascii')
return string.translate(ascii_code_point_filter)
"
python -m timeit -s"$SETUP""re_replace(busy)"
python -m timeit -s"$SETUP""''.join(e for e in busy if in_whitelist(e))"
python -m timeit -s"$SETUP""fast_replace(busy)"
结果:
10000 loops, best of 3: 63 usec per loop
10000 loops, best of 3: 135 usec per loop
100000 loops, best of 3: 4.98 usec per loop
在所有这些方面产生与我的输出完全相同的输出:
@Master_Yoda; 您可能正在使用Python2。OP正在使用Python 3。
好电话,没有注意到这一点。
经过测试,它确实处理了非ascii文本
你为什么不能做这样的事情:
def in_whitelist(character):
return character.isalnum() or character in ['\','/']
line2 = ''.join(e for e in line2 if in_whitelist(e))
根据建议进行编辑以压缩功能。
为了简洁起见,我个人将最后一部分更改为character in [\, ]。
好。 这工作了。 只是必须转义反斜杠[\\, ]
转义字符串文字后为我工作...哦,@ Khaelid同意。
无法完成所有这些操作:(等)