如何编写正则表达式来修复由重复字母组成的单词



我刮了一些pdf,一些厚字体被刮了,如本例所示:

text='and assesses oouurr rreeffoorrmmeedd tteeaacchhiinngg in the classroom'

而不是

"and assesses our reformed teaching in the classroom"

如何解决此问题?我正在尝试使用regex

pattern=r'([a-z])(?=1)'
re.sub(pattern,'',text)
#"and aseses reformed teaching in the clasrom"

我正在考虑将上面的两组分组,并添加单词边界

编辑:这个修复了偶数字母的单词:

pattern=r'([a-z])1([a-z])2'
re.sub(pattern,'12',text)
#"and assesses oouurr reformed teaching in the classroom"

如果字母重复,您可以尝试类似的方法

for w in text.split():
if len(w) %2 != 0:
print(w)
continue
if w[0::2] == w[1::2]:
print(w[0::2])
continue
print(w)

我使用的是一种混合方法:在for循环中构建模式和替换,然后应用regex。所应用的正则表达式从8x2=16个字母的单词一直到3个。

import re
text = 'and assesses oouurr rreeffoorrmmeedd tteeaacchhiinngg in the classroom'
wrd_len = [9,8,7,6,5,4,3,2]
for l in wrd_len:
sub = '\' + '\'.join(map(str,range(1,l+1)))
pattern = '([a-z])\' + '([a-z])\'.join(map(str,range(1,l+1)))
text = re.sub(pattern, sub , text)
text
#and assesses our reformed teaching in the classroom

例如,3个字母单词的正则表达式变为:

re.sub('([a-z])1([a-z])2([a-z])3', '123', text)

顺便说一句,我不能用原始字符串来获得这些反斜杠,实际上我将使用[a-zA-Z]。

我在javascript中找到了运行良好的解决方案:

([a-z])1(?:(?=([a-z])2)|(?<=3([a-z])11))

但在某些情况下,它在python中不起作用,因为lookbacking不能引用组,所以我想出了另一个可以在本例中起作用的解决方案:

([a-z])1(?:(?=([a-z])2)|(?=[^a-z])))

在这里试试

最新更新