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

2024-06-07 07:45:21 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

而不是

"and assesses our reformed teaching in the classroom"

如何解决这个问题?我正在尝试使用正则表达式

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,'\1\2',text)
#"and assesses oouurr reformed teaching in the classroom"

Tags: andthetextinrepdf字体单词
3条回答

我使用的是混合方法:在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

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

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

作为旁注,我无法用原始字符串正确地使用这些反斜杠,实际上我将使用[a-zA-Z]

我在javascript中找到了一个很好的解决方案:

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

但在某些情况下,它在python中不起作用,因为lookbehind无法引用group,所以我提出了另一个在本例中可以起作用的解决方案:

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

试试看here

如果字母重复,您可以尝试这样的方法

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)

相关问题 更多 >

    热门问题