Soy un estudiante de primer año en la universidad, que está tomando una clase de encoding de python. Actualmente estoy trabajando para que un progtwig cuente la cantidad de vocales o consonantes en función de la entrada de un usuario para determinar el modo.
Actualmente, he hecho dos listas, y estoy tratando de averiguar cómo progtwigr Python para contar las vocales / consonantes.
Esto es lo que tengo hasta ahora. Por favor, tenga en cuenta que he trabajado en ambos extremos, y el centro es donde va el conteo.
#=======================================# #Zane Blalock's Vowel/Consonants Counter# #=======================================# print("Welcome to the V/C Counter!") #Make List vowels = list("aeiouy") consonants = list("bcdfghjklmnpqrstvexz") complete = False while complete == False: mode = input("What mode would you like? Vowels or Consonants?: ").lower().strip() print("") print("You chose the mode: " + str(mode)) print("") if mode == "vowels": word = input("Please input a word: ") print("your word was: " + str(word)) print("") choice = input("Are you done, Y/N: ").lower().strip() if choice == "y": complete = True else: print("Ok, back to the top!") elif mode == "consonants": word = input("please input a word: ") print("your word was: " + str(word)) print("") choice = input("Are you done, Y/N: ").lower().strip() if choice == "y": complete = True else: print("Ok, back to the top!") else: print("Improper Mode, please input a correct one") print("Thank you for using this program")
number_of_consonants = sum(word.count(c) for c in consonants) number_of_vowels = sum(word.count(c) for c in vowels)
if mode == "vowels": print(len(filter(lambda x: x in vowels, word))) else: print(len(filter(lambda x: x in consonants, word)))
Así que cronometré mi solución y la de eumiro. El suyo es mejor
>> vc=lambda :sum(word.count(c) for c in vowels) >> vc2=lambda : len(filter(lambda x: x in vowels, word)) >> timeit.timeit(vc, number=10000) 0.050475120544433594 >> timeit.timeit(vc2, number=10000) 0.61688399314880371
Usar regex sería una alternativa:
>>> import re >>> re.findall('[bcdfghjklmnpqrstvwxyz]','there wont be any wovels in the result') ['t', 'h', 'r', 'n', 't', 'b', 'n', 'v', 'l', 's', 'n', 't', 'h', 'r', 's', 'l', 't']
Si tomas su longitud tu problema está resuelto.
text = 'some text' wovels = 'aeiou' consonants = 'bcdfghjklmnpqrstvwxyz' from re import findall wovelCount = len(findall('[%s]' % wovels, text)) consonatCount = len(findall('[%s]' % consonants, text))
Esta es una solución que cuenta las consonantes y las vocales, a la vez que excluye la puntuación explícitamente.
from string import punctuation x = 'This is an example sentence.' table = str.maketrans('', '', punctuation) x = x.translate(table).lower().replace(' ', '') vowels = set('aeiou') consonants = sum(i not in vowels for i in x) vowels = sum(i in vowels for i in x) print(consonants) # 14 print(vowels) # 9
Python 2.6.7 (r267:88850, Jun 27 2011, 13:20:48) [MSC v.1500 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> a = "asfdrrthdhyjkae" >>> vowels = "aeiouy" >>> consonants = "bcdfghjklmnpqrstvexz" >>> nv = 0 >>> nc = 0 >>> for char in a: ... if char in vowels: ... nv += 1 ... elif char in consonants: ... nc += 1 ... >>> print nv 4 >>> print nc 11 >>>
La mayoría de las otras respuestas parecen contar cada carácter por separado y luego resumir los resultados, lo que significa que el código debe repetirse en la cadena de entrada muchas veces y es algo ineficiente. Más eficiente sería contar todas las ocurrencias de todos los personajes de una sola vez, usando una collections.Counter
.
import collections s = "This is an example sentence." counter = collections.Counter(s) consonants = 'bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ' num_consonants = sum(counter[char] for char in consonants) # result: 14 vowels = 'aeiouAEIOU' num_vowels = sum(counter[char] for char in vowels) # result: 9
¿Qué hay de la lista de comprensión con expresiones regulares ?
import re mystr = 'Counting the amount of vowels or consonants in a user input word' len(re.findall('[aeiou]', mystr, flags=re.I)) # gives the number of vowels len(re.findall('[bd]|[fh]|[jn]|[pt]|[vz]', mystr, flags=re.I)) #gives the number of consonants
def main(): vowels = 'aeiou' consonants = 'bcdfghjklmnpqrstvwxyz' txt_input = input('Enter a sentence or a word: ').lower() vowel = sum(txt_input.count(i) for i in vowels) consonant = sum(txt_input.count(i) for i in consonants) print("Number of vowels in the string: ",vowel) print("Number of consonants in the string: ",consonant) main()