首页 > 解决方案 > 在元音+周围辅音处拆分字符串

问题描述

我是编码新手,这是我的第一次尝试。我想将单词从语音语言中分成音节。

用语音语言中的单词组成音节的规则:

考虑所有辅音,直到第一个元音,考虑那个元音。重复。

例子:

m a - r i - a

a - l e - ks a - nd a - r

这就是我已经走了多远:

    word = 'aleksandar'
    vowels = ['a','e','i','o','u']
    consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z']

    for vowel in vowels:

        if vowels in word:

            index_1 = int(word.index(vowel)) - 1
            index_2 = int(word.index(vowel)) + 1

            print(word[index_1:index_2])

        else:

            print(consonants)

IDK出了什么问题,请帮忙!提前致谢 :)

标签: pythonstringsplitslice

解决方案


我已经稍微更改了您的代码,并且效果很好!

word = 'aleksandar'
word = list(word)
vowels = ['a','e','i','o','u']
s = ""
syllables = [ ]
for i in range(len(word)):
    if word[i] not in vowels:
        s = s + word[i]
    else:
        s = s + word[i]
        syllables.append(s)
        s = ""
print(syllables)    

输出是:

['a', 'le', 'ksa', 'nda']

推荐阅读