我想这样做:
a = "Describe"
我想用后面的第二个元音单词分割“Describe”,这样它就变成了“Describe”和“be”。
另一个例子是“Public”
,它应该分为“Pu”
和“blic”
。
我尝试过:
vowel = "AaIiUuEeOo"
consonant = "BbCcDdFfGgHhJjKkLlMmNnPpQqRrSsTtVvWwXxYyZz"
p = []
for char in words[::-1]:
if char in consonant:
p.append(char)
elif char in vokal:
p.append(char)
break
我怎样才能实现这个目标?
最佳答案
您可以使用正则表达式 ^(.*[AaIiUuEeOo])(?=.*[AaIiUuEeOo])(.+)$
。这个想法是捕获一个元音之前的所有内容,后跟另一个元音,以及可选的一些其他字符,这些字符将被放置在第二个捕获组中。
>>> import re
>>> pattern = r"^(.*[AaIiUuEeOo])(?=.*[AaIiUuEeOo])(.+)$"
>>> re.match(pattern, "Describe").groups()
('Descri', 'be')
>>> re.match(pattern, "Public").groups()
('Pu', 'blic')
>>> re.match(pattern, "ibe").groups()
('i', 'be')
>>> re.match(pattern, "ie").groups()
('i', 'e')
如果字符串没有至少两个元音,请确保在对结果调用 groups()
之前测试 None
。
另一个想法是使用 itertools.groupby
这比较笨重,但很有趣,并且可以很好地推广到任何 n
或任何字符集(或迭代,就此而言 - 我在这里坚持使用字符串)。
from itertools import groupby
def nth_from_rear(s, n=2, matches="aeiou"):
def nth_counter(n=2, count=0):
def cb(x):
nonlocal count
if x.lower() in matches:
count += 1
return count >= n
return cb
groups = groupby(s[::-1], key=nth_counter(n))
return ["".join(x)[::-1] for _, x in groups][::-1]
if __name__ == "__main__":
tests = [
["Public", 2],
["Describe", 2],
["ie", 2],
["ibbe", 2],
["Describe", 0],
["Describing", 1],
["Describe", 3],
["ababbaba", 4],
]
for s, n in tests:
print(s.rjust(10), n, nth_from_rear(s, n))
输出:
Public 2 ['Pu', 'blic']
Describe 2 ['Descri', 'be']
ie 2 ['i', 'e']
ibbe 2 ['i', 'bbe']
Describe 0 ['Describe']
Describing 1 ['Describi', 'ng']
Describe 3 ['De', 'scribe']
ababbaba 4 ['a', 'babbaba']
关于python - 通过单词后面的第二个元音从字符串中获取子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59015651/