Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
计算字符串Python中的元音_Python - Fatal编程技术网

计算字符串Python中的元音

计算字符串Python中的元音,python,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 : a

我试图计算字符串中特定字符的出现次数,但输出是错误的

这是我的密码:

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
您想要的可以非常简单地这样做:

>>> mystr = input("Please type a sentence: ")
Please type a sentence: abcdE
>>> print(*map(mystr.lower().count, "aeiou"))
1 1 0 0 0
>>>
如果您不知道,这里有一个参考,另一个在上。

使用

计数器
仅在Python 2.7+中可用。一个应该在Python2.5上工作的解决方案将利用


如果stri中的A或A
表示
如果A或(stri中的A)
如果为真,或(stri中的A)
始终为
,并且对于每个
如果
语句都相同

您想说的是
如果一个在stri中或一个在stri中

这是你的错误。不是唯一的一个-您并没有真正计算元音,因为您只检查字符串是否包含元音一次

另一个问题是,您的代码远不是最好的方法,请参阅,例如,此:。您将在那里找到一些很好的解决方案,这些解决方案可以很容易地用于您的特定情况。我认为,如果您仔细阅读第一个答案,您将能够以正确的方式重写代码

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

(记住空格s)

我写了一个用于计算元音的代码。你可以用它来计算你选择的任何字符。我希望这有帮助!(用Python 3.6.0编写)


对于那些寻找最简单解决方案的人,这里有一个

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)

这对我来说很有效,而且还可以计算辅音数(可以认为是一种奖励),但是,如果你真的不想计算辅音数,那么你所要做的就是删除最后一个for循环和顶部的最后一个变量

她的代码是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))
假设

S=“组合”

印刷品: ['o','i','a','i','o']

对于您的案例,请使用一句话(案例1):

txt=“诸如此类……”

案例2

从集合导入defaultdict
def count_元音(单词):
元音='aeiouAEIOU'
count=defaultdict(int)#初始计数器
对于word中的字符:
如果元音中有字符:
计数[char]+=1
返回计数
一种计算单词元音的pythonic方法,与
java
c++
不同,实际上不需要预处理单词字符串,也不需要
str.strip()
str.lower()
。但是如果您想不区分大小写地计算元音,那么在进入for循环之前,请使用
str.lower()

您可以在此处测试此代码:

所以祝你玩得开心,希望对你有点帮助。

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")

您可以使用regex和dict理解:

import re
s = "aeiouuaaieeeeeeee"
vowels = ["a", "e", "i", "o", "u"]

def vowel_counter(str):
  return len([char for char in str if char in vowels])

print(vowel_counter("abracadabra"))
# 5
正则表达式函数findall()返回一个包含所有匹配项的列表

这里x是键,regex返回的列表长度是该字符串中每个元音的计数,请注意,regex将找到您引入“aeiou”字符串的任何字符

返回:

{'a': 3, 'e': 9, 'i': 2, 'o': 1, 'u': 2}
从集合导入计数器
计数=计数器()
inputString=str(输入(“请键入句子:”)
对于输入字符串中的i:
如果我在“aeiouAEIOU”中:
计数更新(一)
打印(计数)

另一个具有列表理解功能的解决方案:

import re
s = "aeiouuaaieeeeeeee"
vowels = ["a", "e", "i", "o", "u"]

def vowel_counter(str):
  return len([char for char in str if char in vowels])

print(vowel_counter("abracadabra"))
# 5

这是一个简单的,不要觉得它很复杂,在python中搜索三元for循环,你会得到它的

打印(总和([1表示输入中的元素(),如果“aeiouAEIOU”中的元素])

借助此代码,您可以在字符串中找不到任何元音和辅音。我希望这会有帮助


stri
在哪里声明?您是如何生成输出的?输入是什么?要计数字符是一个字符串,请使用计数方法:
'aabccc'。计数('c')
您忘记的
y
的可能重复项。这是否回答了您的问题?你可以做
counts={i:0 for i in'aeiouAEIOU'}
而不是
counts={}.fromkeys('aeiouAEIOU',0)
我认为你可以做
d=defaultdict(int)
。你现在已经发布了三个答案,其中包含代码块,没有解释或详细说明为什么你的解决方案是正确的答案。请不要只发布代码块。欢迎使用So。然而,你的答案有几个问题:1)它实际上没有向OP解释任何事情2)它与另一个答案重复(OP试图确定的每个元音的计数也没有被打破)你能再添加一点注释吗?你可以通过
string.lower()
而不仅仅是遍历普通输入字符串,因为OP似乎希望能够处理大写字母。此外,如果“aeiou”中的字符为char,则元音测试可以是
。这是一个很好的建议。谢谢请阅读这篇文章以提供高质量的答案。如果只包含代码而不设置格式,这将不是一个好的答案。计算“字符串”中每个元音出现的次数,并将其放入列表中,即[1a,0e,1i,1o,0u]。lower()将“string”更改为小写,因此如果有大写元音,它也会对其进行计数。在input()之后是否需要str()函数?另外,如果您决定使用.count()函数,请将其与用户输入的每个元素的len()的循环一起使用。这只计算句子中元音的总数,而OP希望获得特定字符的计数。你可以通过指定一个元音只使用<代码>元音< /代码>,但是仍然有一个缺少的元组来获得多元音的多个计数。你看到了吗?你应该在元音中做“如果字母。低音())来考虑大写字母VoelsSes,这不是最简单的。这是:
count=len(关于findall(“[aeiouAEIOU]”,句子))
。但问题需要每个字母单独计数,因此两种解决方案都不正确。或者,更简单地说:
print(sum([1代表输入中的ele(),如果“AEIOU”中的ele.upper()])
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))
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
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)
string1='I love my India'

vowel='aeiou'

for i in vowel:
  print i + "->" + str(string1.count(i))
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)
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))
>>> string = "aswdrtio"
>>> [string.lower().count(x) for x in "aeiou"]
[1, 0, 1, 1, 0]
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)
import re
print re.findall('a|e|i|o|u', S)
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))
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))
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"))
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")
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()))
import re
s = "aeiouuaaieeeeeeee"
foo = {x: len(re.findall(f"{x}", s)) for x in "aeiou"}
print(foo)
{'a': 3, 'e': 9, 'i': 2, 'o': 1, 'u': 2}
vowels = ["a", "e", "i", "o", "u"]

def vowel_counter(str):
  return len([char for char in str if char in vowels])

print(vowel_counter("abracadabra"))
# 5
def vowel_count(string):
    
    string = string.lower()
    count = 0
    vowel_found = False 
    
    for char in string:
        if char in 'aeiou': #checking if char is a vowel
            count += 1
            vowel_found = True
            
    if vowel_found == False:
        print(f"There are no vowels in the string: {string}")
            
    return count

string = "helloworld"

result = vowel_count(string) #calling function

print("No of vowels are: ", result)
char = input("Enter your string:")
vowel = 0
const = 0
chars = char.lower()
list = []
list2 = []
for i in range(0, len(chars)):
    if(chars[i]!=' '):
        if(chars[i]=='a' or chars[i]=='e' or chars[i]=='i' or chars[i]=='o' or chars[i]=='u'):
            vowel = vowel+1
            list.append(chars[i])
        else:
            const = const+1
            list2.append(chars[i])
while True:
    if vowel==1:
        print("Vowel are:", vowel, list)
    if vowel>1:
        print("Vowels are:", vowel, list)
    if const==1:
        print("Constant are:", const, list2)
    if const>1:
        print("Constants are:", const, list2)
        break
    else:
        break