以下代码在每次当前字母为辅音而下一个字母为元音时,将字符串作为输入并将其拆分为字符串列表。这很慢,我该如何改善?谢谢
def count_syllables(word):
word= list(word)
vowels= {"a":1,"e":2,"i":3,"o":4,"u":5,"y":6,"j":7}
s = word[0]
syllables = [ ]
count = 1
l_max = len(word)
while count != l_max :
if word[count] not in vowels and word[count-1] in vowels:
syllables.append(s)
s = word[count]
count += 1
else:
s += word[count]
count += 1
syllables.append(s)
value1 = len(syllables)
value2 = syllables[-1]
return (value1, value2)
答案 0 :(得分:0)
您可以尝试使用正则表达式
import re
def count_syllables(word):
syllables = re.findall("[bcdfghjklmnpqrstvwxy]+[aeiouy]*", word)
return len(syllables), syllables
答案 1 :(得分:0)
尝试一下
def count_syl(word:str):
vowels = set("eyuioa")
syllables = []
count = 0
i = 0
while i < len(word) - 1:
if word[i] in vowels and word[i + 1] not in vowels:
syb = word[count:i+1]
count = i + 1
syllables.append(syb)
i += 1
syllables.append(word[count:])
return (len(syllables), syllables)