在Python中使用正则表达式的单词压缩函数

0 投票
2 回答
821 浏览
提问于 2025-04-17 06:44

有人能告诉我为什么我在这个Python代码中使用的正则表达式似乎没有得到正确的结果吗?我本以为,比如说,单词“about”中的第一个元音字母不应该消失。谢谢。

>>> sentence = "But the third reason Americans should care about Europe is more important    even than the risk of a renewed financial crisis."
>>> regexp = r'^[AEIOUaeiou]+|[AEIOUaeiou]+$|[^AEIOUaeiou]'
>>> def compress(word):
...     pieces = re.findall(regexp, word)
...     return ''.join(pieces)
>>> compress(sentence)
'Bt th thrd rsn mrcns shld cr bt rp s mr mprtnt vn thn th rsk f  rnwd fnncl crss.'

2 个回答

1

'^[AEIOUaeiou]+' 这个表达式可以用来匹配字符串开头的一连串元音字母。

'[AEIOUaeiou]+$' 这个表达式则是用来匹配字符串结尾的一连串元音字母。

'[^AEIOUaeiou]' 这个表达式可以用来匹配任何不是元音字母的字符。

如果是 '[^AEIOUaeiou]+',那么它就可以匹配一连串的非元音字母字符。

目前你使用的这个正则表达式,只能一次匹配一个非元音字母字符。

你的评论解释了你想要做的事情。
其实没有必要使用正则表达式来完成这个任务;我觉得用正则表达式来解决这个问题可能会更难,或者至少会更复杂。

这样能满足你的需求吗?:

def compress(word):
    if len(word)<3:
        yield word
    else:
        yield word[0]
        for c in word[1:-1]:
            if c not in 'AEIOUaeiou':
                yield c
        yield word[-1]


print ' '.join(''.join(compress(word)) for word in sentence.split())
4

符号 ^ 和 $ 是用来定位整个字符串的开头和结尾的,也就是说,它们不是用来定位每个单词的开头和结尾,而是定位整句话的开头和结尾。当这句话只有一个单词“about”时,它的表现就像你预期的那样。我觉得你可能想要定位到单词的边界(\b)而不是整句话的边界。

http://www.regular-expressions.info/wordboundaries.html

这样可能会达到你想要的效果:

regexp = r'\b[AEIOUaeiou]+|[AEIOUaeiou]+\b|[^AEIOUaeiou]'

撰写回答