【问题标题】:Remove continuous occurrence of vowels together in a string using Python使用 Python 删除字符串中连续出现的元音
【发布时间】:2021-03-05 11:26:59
【问题描述】:

我有一个如下字符串:

"i'm just returning from work. *oeee* all and we can go into some detail *oo*. what is it that happened as far as you're aware *aouu*"

上面有一些垃圾字符(用“*”标记突出显示)。我所能观察到的只是垃圾字符是一堆元音编织在一起的。现在,我需要删除任何前后有空格且只有元音(如 oeee、aouu 等)且长度为 2 或更多的单词。我如何在 python 中实现这一点?

目前,我构建了一个元组以包含替换词,如 ((" oeee "," "),(" aouu "," ")),并通过 for 循环将其发送到替换。但是如果这个词是'oeeee',我需要在元组中添加一个新项目。一定有更好的办法。

P.S:实际文本中不会有“*”。我只是把它放在这里突出显示。

【问题讨论】:

  • 试试:(?<=\s)[aeiouAEIOU]{2,}(?=\s)
  • 尝试了 text.replace("(?
  • 如果你使用re.sub()会发生什么?
  • 这是我得到的信息:“我刚下班回来。我们可以详细介绍一下哦。就你所知,发生了什么事情”。第一个垃圾字符被删除。
  • 您需要在 anubhava 建议的正则表达式中将 \s 替换为 \b。那么它应该可以正常工作。

标签: python python-3.x regex


【解决方案1】:

您需要使用re.sub 在python 中进行正则表达式替换。你应该使用这个正则表达式:

\b[aeiou]{2,}\b

将匹配单词中的 2 个或多个元音序列。我们使用\b 来匹配单词的边界,因此它将匹配字符串的开头和结尾(在您的字符串中,aouu)以及与标点符号相邻的单词(在您的字符串中,oo)。如果您的文本也可能包含大写元音,请使用 re.I 标志忽略大小写:

import re

text = "i'm just returning from work. oeee all and we can go into some detail oo. what is it that happened as far as you're aware aouu"
print(re.sub(r'\b[aeiou]{2,}\b', '', text, 0, re.I))

输出

i'm just returning from work.  all and we can go into some detail . what is it that happened as far as you're aware 

【讨论】:

  • 更好@JvdV
  • 为什么不只是\b[aeiou]{2,}\b
  • @JvdV 谢谢 - 有那么一刻精神失常。我已经更新了答案。
  • @anubhava 你也是正确的,我已经更新了答案。
猜你喜欢
  • 1970-01-01
  • 2019-01-18
  • 2020-11-22
  • 1970-01-01
  • 2018-08-27
  • 2017-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多