我一直在试图为辅音+无声的"e“音节减法写一条规则。然而,我的方法效率极低,在它自己的if-else语句中单独使用每个辅音。有人有办法一次检查所有辅音吗?
def syllable_count(word):
word = word.lower()
count = 0
vowels = "aeiouy"
consonants = "bcdfghjklmnpqrstvwxz"
if word[0] in vowels:
count += 1
for index in range(1, len(word)):
if word[index] in vowels and word[index - 1] not in vowels:
count += 1
if word.endswith(consonants[15] + "e"):
count -= 1
else:
if word.endswith(consonants[15] + "es"):
count -= 1
# ... etc etc...
if count == 0:
count += 1
return count
发布于 2022-06-19 21:25:57
你的意思是你想扩大你的if word.endswith(consonants[15] + "e")
的例子,检查所有辅音在一次?如果你想说“如果这个词以辅音+e结尾”,那就用它来代替检查consonants[15]
if any(word.endswith(consonant + "e") for consonant in consonants)
另外,如果它应该是“辅音+e或es",那么:
if any(word.endswith(consonant + "e") or word.endswith(consonant + "es") for consonant in consonants)
发布于 2022-06-19 21:11:28
下面是代码+内部的解释:
import re
# inside the [ ... ] you can choose any letter once
# the letter e outside the [ ... ] means it must be followed by an e
pattern = "[bdfghjklmnpqrstvwxz]e"
words = ["letter", "orchestra", "person"]
count = [
len(["match" for m in re.finditer(pattern, w)])
for w in words
]
print(count)
https://stackoverflow.com/questions/72681924
复制