2013-04-14 38 views
1

这是迄今为止的代码。这个程序应该要求用户输入一个单词并确定其中的元音/辅音的数量。用户完成后,程序应该给他们元音/辅音的平均数量。一些开始的代码是不同的(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() 

回答

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 
+0

请问我的高清VOCO()之前或之后那去了?我对事物的顺序感到困惑。 –

+0

@BrandonJones查看我编辑的代码。 –

+0

谢谢。如果你不介意的话,我会用你的一些代码修改我的代码。我会+1,但我没有足够的代表。 –