Python 2.7 先计算元音,再计算辅音
我想数一数课文中的元音,这是我能做到的。但是我还想计算元音后面跟一个辅音的数量,以及元音后面跟一个元音的数量。有人能帮我吗 这是我到目前为止所知道的,但它表明我在元音中使用I+1的行的语法无效Python 2.7 先计算元音,再计算辅音,python-2.7,Python 2.7,我想数一数课文中的元音,这是我能做到的。但是我还想计算元音后面跟一个辅音的数量,以及元音后面跟一个元音的数量。有人能帮我吗 这是我到目前为止所知道的,但它表明我在元音中使用I+1的行的语法无效 s = "text" vowels = set("aeuio") consonants = set("qwrtypsdfghjklzxcvbnm") vowelcount=0 vowelvowelcount=0 consonantcount=0 consvowelcount=0 consconscoun
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)
如果对s中的i使用
,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
# ...
适用于范围内的i(透镜-1):
如果元音中的s[i]和辅音中的s[i+1]:
元音计数+=1
elif s[i]表示元音,s[i+1]表示元音:
元音owerCount+=1
#…
在这里,我们使用range(..)
迭代所有索引,直到(但不包括)len(s)-1
。对于每个索引i
,我们检查i
位置s
中的字符(即s[i]
)是否为元音,下一个字符s[i+1]
是否为谐音。我喜欢威廉的答案。我有另一个选择。在这种情况下,我可能想使用枚举
for i, char in enumerate(s[:-1]):
if char in vowels and s[i+1] in vowels:
vowelvowelcount +=1
您将需要使用字符串切片并计算通过字符串的路径。类似于如果s[2:3]在元音中,s[3:4]在元音中。@mba12:但是s[3:4]
相当于s[3]
。@WillemVanOnsem您是正确的,您的语法也更清晰。在看到您的答案之前,我写了我的评论。如果没有另一个if
语句,这将不起作用,因为I+1
在上一次迭代中将超出s
的范围。@WillemVanOnsem噢,忘记添加s[:-1]
。谢谢也许您可以使用枚举(s[:-1],1)
,这样您就可以将+1
保存为i+1
。