Подтвердить что ты не робот

Графовые гласные в String Python

Я пытаюсь подсчитать количество вхождений определенных символов в строке, но результат неправильный.

Вот мой код:

inputString = str(input("Please type a sentence: "))
a = "a"
A = "A"
e = "e"
E = "E"
i = "i"
I = "I"
o = "o"
O = "O"
u = "u"
U = "U"
acount = 0
ecount = 0
icount = 0
ocount = 0
ucount = 0

if A or a in stri :
     acount = acount + 1

if E or e in stri :
     ecount = ecount + 1

if I or i in stri :
    icount = icount + 1

if o or O in stri :
     ocount = ocount + 1

if u or U in stri :
     ucount = ucount + 1

print(acount, ecount, icount, ocount, ucount)

Если я введу букву A, выход будет: 1 1 1 1 1

4b9b3361

Ответ 1

То, что вы хотите, можно сделать просто так:

>>> mystr = input("Please type a sentence: ")
Please type a sentence: abcdE
>>> print(*map(mystr.lower().count, "aeiou"))
1 1 0 0 0
>>>

В случае, если вы не знаете их, вот ссылка на map и один на *.

Ответ 2

>>> sentence = input("Sentence: ")
Sentence: this is a sentence
>>> counts = {i:0 for i in 'aeiouAEIOU'}
>>> for char in sentence:
...   if char in counts:
...     counts[char] += 1
... 
>>> for k,v in counts.items():
...   print(k, v)
... 
a 1
e 3
u 0
U 0
O 0
i 2
E 0
o 0
A 0
I 0

Ответ 3

def countvowels(string):
    num_vowels=0
    for char in string:
        if char in "aeiouAEIOU":
           num_vowels = num_vowels+1
    return num_vowels

(помните расстояние s)

Ответ 4

data = str(input("Please type a sentence: "))
vowels = "aeiou"
for v in vowels:
    print(v, data.lower().count(v))

Ответ 5

Используйте Counter

>>> from collections import Counter
>>> c = Counter('gallahad')
>>> print c
Counter({'a': 3, 'l': 2, 'h': 1, 'g': 1, 'd': 1})
>>> c['a']    # count of "a" characters
3

Counter доступен только в Python 2.7+. Решение, которое должно работать на Python 2.5, будет использовать defaultdict

>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> for c in s:
...     d[c] = d[c] + 1
... 
>>> print dict(d)
{'a': 3, 'h': 1, 'l': 2, 'g': 1, 'd': 1}

Ответ 6

if A or a in stri означает if A or (a in stri), который if True or (a in stri), который всегда True, и тот же для каждого вашего оператора if.

То, что вы хотели сказать, if A in stri or a in stri.

Это твоя ошибка. Не единственный - вы на самом деле не считаете гласные, так как вы только проверяете, содержит ли строка один раз.

Другая проблема заключается в том, что ваш код далеко не лучший способ сделать это, пожалуйста, см., например, следующее: Считать гласные с исходного ввода. Здесь вы найдете несколько приятных решений, которые легко могут быть приняты для вашего конкретного случая. Я думаю, что если вы подробно рассмотрите первый ответ, вы сможете правильно переписать свой код.

Ответ 7

count = 0 

string = raw_input("Type a sentence and I will count the vowels!").lower()

for char in string:

    if char in 'aeiou':

        count += 1

print count

Ответ 8

Для краткости и удобочитаемости используйте понимание словаря.

>>> inp = raw_input() # use input in Python3
hI therE stAckOverflow!
>>> search = inp.lower()
>>> {v:search.count(v) for v in 'aeiou'}
{'a': 1, 'i': 1, 'e': 3, 'u': 0, 'o': 2}

В качестве альтернативы вы можете рассмотреть именованный кортеж.

>>> from collections import namedtuple
>>> vocals = 'aeiou'
>>> s = 'hI therE stAckOverflow!'.lower()
>>> namedtuple('Vowels', ' '.join(vocals))(*(s.count(v) for v in vocals))
Vowels(a=1, e=3, i=1, o=2, u=0)

Ответ 9

Я написал код, используемый для подсчета гласных. Вы можете использовать это, чтобы считать любого выбранного вами персонажа. Надеюсь, это поможет! (закодировано в Python 3.6.0)

while(True):
phrase = input('Enter phrase you wish to count vowels: ')
if phrase == 'end': #This will to be used to end the loop 
    quit() #You may use break command if you don't wish to quit
lower = str.lower(phrase) #Will make string lower case
convert = list(lower) #Convert sting into a list
a = convert.count('a') #This will count letter for the letter a
e = convert.count('e')
i = convert.count('i')
o = convert.count('o')
u = convert.count('u')

vowel = a + e + i + o + u #Used to find total sum of vowels

print ('Total vowels = ', vowel)
print ('a = ', a)
print ('e = ', e)
print ('i = ', i)
print ('o = ', o)
print ('u = ', u)

Ответ 10

Для тех, кто ищет самое простое решение, здесь

vowel = ['a', 'e', 'i', 'o', 'u']
Sentence = input("Enter a phrase: ")
count = 0
for letter in Sentence:
    if letter in vowel:
        count += 1
print(count)

Ответ 11

>>> string = "aswdrtio"
>>> [string.lower().count(x) for x in "aeiou"]
[1, 0, 1, 1, 0]

Ответ 12

sentence = input("Enter a sentence: ").upper()
#create two lists
vowels = ['A','E',"I", "O", "U"]
num = [0,0,0,0,0]

#loop through every char
for i in range(len(sentence)):
#for every char, loop through vowels
  for v in range(len(vowels)):
    #if char matches vowels, increase num
      if sentence[i] == vowels[v]:
        num[v] += 1

for i in range(len(vowels)):
  print(vowels[i],":", num[i])

Ответ 13

count = 0
s = "azcbobobEgghakl"
s = s.lower()
for i in range(0, len(s)):
    if s[i] == 'a'or s[i] == 'e'or s[i] == 'i'or s[i] == 'o'or s[i] == 'u':
        count += 1
print("Number of vowels: "+str(count))

Ответ 14

string1 = 'Я люблю свою Индию' гласный = 'AEIOU' для я в гласных: print я + "- > " + str (string1.count(i))

Ответ 15

Это работает для меня, а также подсчитывает согласные (подумайте об этом как о бонусе), однако, если вы действительно не хотите, чтобы подсчет согласных был всего, что вам нужно сделать, это удалить последний цикл и последнюю переменную в верх.

Ее код python:

data = input('Please give me a string: ')
data = data.lower()
vowels = ['a','e','i','o','u']
consonants = ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']
vowelCount = 0
consonantCount = 0


for string in data:
    for i in vowels:
        if string == i:
            vowelCount += 1
    for i in consonants:
        if string == i:
            consonantCount += 1

print('Your string contains %s vowels and %s consonants.' %(vowelCount, consonantCount))

Ответ 16

Simplest Answer:

inputString = str(input("Please type a sentence: "))

vowel_count = 0

inputString =inputString.lower()

vowel_count+=inputString.count("a")
vowel_count+=inputString.count("e")
vowel_count+=inputString.count("i")
vowel_count+=inputString.count("o")
vowel_count+=inputString.count("u")

print(vowel_count)

Ответ 17

Предположим,

S = "Комбинация"

import re
print re.findall('a|e|i|o|u', S)

Печать: ['o', 'i', 'a', 'i', 'o']

Для вашего случая в предложении (Case1):

txt = "бла-бла-бла...."

import re
txt = re.sub('[\r\t\n\d\,\.\!\?\\\/\(\)\[\]\{\}]+', " ", txt)
txt = re.sub('\s{2,}', " ", txt)
txt = txt.strip()
words = txt.split(' ')

for w in words:
    print w, len(re.findall('a|e|i|o|u', w))

Вариант 2

import re,  from nltk.tokenize import word_tokenize

for w in work_tokenize(txt):
        print w, len(re.findall('a|e|i|o|u', w))

Ответ 18

from collections import defaultdict


def count_vowels(word):
    vowels = 'aeiouAEIOU'
    count = defaultdict(int)   # init counter
    for char in word:
        if char in vowels:
            count[char] += 1
    return count

Питонический способ подсчета гласных в слове, не как в java или c++, на самом деле не нужно предварительно обрабатывать строку слова, нет необходимости в str.strip() или str.lower(). Но если вы хотите считать гласные без str.lower() регистра, то прежде чем идти в цикл for, используйте str.lower().

Ответ 19

vowels = ["a","e","i","o","u"]

def checkForVowels(some_string):
  #will save all counted vowel variables as key/value
  amountOfVowels = {}
  for i in vowels:
    # check for lower vowel variables
    if i in some_string:
      amountOfVowels[i] = some_string.count(i)
    #check for upper vowel variables
    elif i.upper() in some_string:
      amountOfVowels[i.upper()] = some_string.count(i.upper())
  return amountOfVowels

print(checkForVowels("sOmE string"))

Вы можете проверить этот код здесь: https://repl.it/repls/BlueSlateblueDecagons

Так что повеселись надежда помогла немного.

Ответ 20

...

vowels = "aioue"
text = input("Please enter your text: ")
count = 0

for i in text:
    if i in vowels:
        count += 1

print("There are", count, "vowels in your text")

...

Ответ 21

def vowels():
    numOfVowels=0
    user=input("enter the sentence: ")
    for vowel in user:
        if vowel in "aeiouAEIOU":
            numOfVowels=numOfVowels+1
    return numOfVowels
print("The number of vowels are: "+str(vowels()))

Ответ 22

def count_vowel():
    cnt = 0
    s = 'abcdiasdeokiomnguu'
    s_len = len(s)
    s_len = s_len - 1
    while s_len >= 0:
        if s[s_len] in ('aeiou'):
            cnt += 1
        s_len -= 1
    print 'numofVowels: ' + str(cnt)
    return cnt

def main():
    print(count_vowel())

main()

Ответ 23

count = 0
name=raw_input("Enter your name:")
for letter in name:
    if(letter in ['A','E','I','O','U','a','e','i','o','u']):
       count=count + 1
print "You have", count, "vowels in your name."

Ответ 24

  1 #!/usr/bin/python
  2 
  3 a = raw_input('Enter the statement: ')
  4 
  5 ########### To count number of words in the statement ##########
  6 
  7 words = len(a.split(' '))
  8 print 'Number of words in the statement are: %r' %words 
  9 
 10 ########### To count vowels in the statement ##########
 11 
 12 print '\n' "Below is the vowel count in the statement" '\n'
 13 vowels = 'aeiou'
 14 
 15 for key in vowels:
 16     print  key, '=', a.lower().count(key)
 17