这是我到目前为止的代码。该程序应该询问用户一个单词并确定其中的元音/辅音量。用户完成后,该程序应该给他们平均元音/辅音数量。一些开头的代码是不同的(V
和C
之间不同),因为我试图找出哪些可行
#Okay, this is the updated version of the code where I combined @AshwiniChaudhary 's code and mine
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 :(得分: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