【发布时间】:2020-11-20 15:15:11
【问题描述】:
给定一个文本,我想进行一些修改:
- 替换句首的大写字符。
- 删除
’或'等字符(不添加空格) - 删除不需要的字符,例如
³或?,!.(并替换为空格)
def multiple_replace(text):
# first sub so words like can't will change to cant and not can t
first_strip=re.sub("[’']",'',text)
def cap(match):
return (match.group().lower())
p = re.compile(r'((?<=[\.\?!]\s)(\w+)|(^\w+))')
#second sub to change all words that begin a sentence to lowercase
second_strip = p.sub(cap,first_strip)
# third_strip is to remove all . from text unless they are used in decimal numbers
third_strip= re.sub(r'(?<!\d)\.|\.(?!\d)','',second_strip)
# fourth strip to remove unexpected char that might be in text for example !,?³ and replace with whitespace
forth_strip=re.sub('[^A-Za-z0-9@#_$&%]+',' ', third_strip)
return forth_strip
我想知道是否有更有效的方法来做到这一点?因为我要检查文本 4 次,所以它可以采用正确的格式供我解析。这似乎很多,尤其是在有数百万个文档的情况下。有没有更有效的方法来做到这一点?
【问题讨论】:
-
没有什么明显的想法,但这可能是一个 XY 问题,因为您提到您正在尝试“解析”某些东西。如果您显示输入的代表性 sn-p 以及您想要的最终输出以及您尝试实现的转换的解释,则可能有更好的方法可以完全避免这种特殊方法。
-
解析的时间可能会超过“清理”文本的时间,在这种情况下,提高清理效率没有多大意义。 “过早的优化是编程中万恶(或至少是大部分)的根源。” -克努斯