我正在嘗試從字串中提取所有元音組并獲取每個元音組的索引。對于單詞='britain'中的ex,元音組是'i'和'ai',字串中的索引是2和4。我想創建兩個串列來跟蹤元音組和索引細繩。也許有一種方法可以使用 regex 或 itertools groupby
到目前為止,這是我的代碼:
first='phoebe'
vowels=['a','e','i','o','u']
char=""
lst=[]
for i in range(len(first)-1):
if first[i] in vowels:
char =first[i]
if first[i] not in vowels:
lst.append(char)
char=""
uj5u.com熱心網友回復:
您可以使用正則運算式執行此操作:
import re
s = 'fountain of youth'
indices = []
strings = []
for m in re.finditer(r'[aeiou] ', s):
indices.append(m.start())
strings.append(m.group())
indices, strings
# ([1, 5, 9, 13], ['ou', 'ai', 'o', 'ou'])
作為壓縮迭代器執行此操作并不難,但如果字串可能沒有元音,則需要小心
uj5u.com熱心網友回復:
first = 'phoebe'
vowels = ['a','e','i','o','u']
vowelGroup = ""
vowelGroups = []
indices = []
index = -1
for i in range(len(first)): #Don't do -1 here otherwise you would miss last 'e' from 'phoebe'
if first[i] in vowels:
vowelGroup = first[i]
if index == -1:
index = i
elif index != -1:
vowelGroups.append(vowelGroup)
indices.append(index)
vowelGroup = ""
index = -1
if index != -1:
vowelGroups.append(vowelGroup)
indices.append(index)
print(vowelGroups, indices)
uj5u.com熱心網友回復:
你可以這樣做itertools.groupby,對字母是否是元音進行分組,然后從 groupby 物件中提取索引和字串:
import itertools
vw = itertools.groupby(enumerate(first), key=lambda t:t[1] in vowels)
vgrps = [(k, list(g)) for k, g in vw if k]
indices = [g[1][0][0] for g in vgrps]
strings = [''.join(t[1] for t in g[1]) for g in vgrps]
輸出:
[2, 5]
['oe', 'e']
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/492017.html
標籤:Python python-3.x 正则表达式 列表 算法
