在用户输入之后,我似乎无法找到平均辅音/元音

时间:2013-04-14 19:06:14

标签: python average

这是我到目前为止的代码。该程序应该询问用户一个单词并确定其中的元音/辅音量。用户完成后,该程序应该给他们平均元音/辅音数量。一些开头的代码是不同的(VC之间不同),因为我试图找出哪些可行

#Okay, this is the updated version of the code where I combined @AshwiniChaudhary 's code and mine

现在我得到一个IndexError:元组索引超出范围

我试着在这里和其他一些网站上查找,但是没有真正找到答案,我不想在这里问两次同样的问题

print("Hello!")
import sys
import re


def VOCO():
VOCO = input("Search for VOWELS or CONSONANTS: ")

if VOCO == "VOWELS":
    VOW = input("Please input word for VOWEL counting: ")
    re.findall(r'[aeiouAEIOU]', VOW)
    V = int(len(re.findall(r'[aeiouAEIOU]', VOW)))
    print(V)


elif VOCO == "CONSONANTS":
    CON = input("Please input word for CONSONANT counting: ")
    re.findall(r'[bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ]', CON)
    C = int(len(re.findall(r'[bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ]', CON)))
    print(C)

else:
    print("Please use either VOWELS or CONSONANTS in selection.")
from string import ascii_lowercase as al
def find_vo_cons2(strs,val):
    vowels="aeiou"
    consonants=set(al)-set(vowels) #set containing only consonants   
    le=float(len(strs))

    vowel_count=0
    consonant_count=0

    for x in strs:
        if x.lower() in vowels:
            vowel_count+=1
        elif x.lower() in consonants:
            consonant_count+=1
    if val in ("V","v"):
        return vowel_count/le
    elif val in ("C","c"):
        return consonant_count/le


def CNT(): True or False
CNT = input("Would you like to continue (YES/NO)? ")

if CNT() : "YES"
condition(True)
VOCO()

else:
        strs = (VOW or CON)
        print("The average of {0} count is {1}".format(find_vo_cons2(strs,VOCO)))
        sys.exit
VOCO()
while True:
    VOCO()

1 个答案:

答案 0 :(得分:0)

我认为你不使用regex也是这样做的:

from string import ascii_lowercase as al
def find_vo_cons(strs,val):
    vowels="aeiou"
    consonants=set(al)-set(vowels) #set containing only consonants   
    le=float(len(strs))

    vowel_count=0
    consonant_count=0

    for x in strs:
        if x.lower() in vowels:
            vowel_count+=1
        elif x.lower() in consonants:
            consonant_count+=1

    if val in ("V","v"):
        return vowel_count/le
    elif val in ("C","c"):
        return consonant_count/le

def main():
    VOCO = input("Search for VOWELS(v) or CONSONANTS(c): ")
    dic={"v":"Vowels","c":"Consonants"}
    strs=  input("Enter the string: ")
    print ("The average of {0} count is {1}".format(dic[VOCO.lower()],find_vo_cons(strs,VOCO)))

main()

<强>输出:

~$ python3 so.py
Search for VOWELS(v) or CONSONANTS(c): v
Enter the string: foObAr
The average of Vowels count is 0.5

~$ python3 so.py
Search for VOWELS(v) or CONSONANTS(c): c
Enter the string: qwertyuiop
The average of Consonants count is 0.6