我想用文本计算元音,我可以做。但我也想计算辅音后面的元音数量和元音后跟元音的数量。有人可以帮我吗?
这是我到目前为止的内容,但它表示我在元音中使用i + 1的行的语法无效。
s = "text"
vowels = set("aeuio")
consonants = set("qwrtypsdfghjklzxcvbnm")
vowelcount=0
vowelvowelcount=0
consonantcount=0
consvowelcount=0
consconscount=0
vowelconscount=0
for i in s:
if i in vowels:
vowelcount += 1
if i in consonants:
consonantcount +=1
for i in s:
if (i in vowels,and i+1 in vowels):
vowelvowelcount +=1
print ("number of vowels:", vowelcount)
print ("number of consonants:", consonantcount)
print ("number of vowels followed by vowels:", vowelvowelcount)
答案 0 :(得分:1)
如果您使用for i in s
,则i
不是索引:它是一个字符。解决此问题的一种快速方法是使用:
for i in range(len(s)-1):
if s[i] in vowels and s[i+1] in consonants:
vowelconscount += 1
elif s[i] in vowels and s[i+1] in vowels:
vowelvowelcount += 1
# ...
在这里,我们使用range(..)
迭代所有索引,但不包括len(s)-1
。对于每个索引i
,我们会检查s
位置i
(即s[i]
)中的字符是vowels
还是下一个字符{{1}是一个辅音。
答案 1 :(得分:1)
我喜欢Willem的回答。我有另一种选择。在这种情况下,我可能想要使用enumerate
。
for i, char in enumerate(s[:-1]):
if char in vowels and s[i+1] in vowels:
vowelvowelcount +=1