在Python中计算i个或多个元音单词的函数?

2024-10-01 17:23:33 发布

您现在位置:Python中文网/ 问答频道 /正文

在下面的代码中,问题13a要求我计算一个字符串中有多少个元音。(我不必在作业中调用这个函数)但我调用它是为了测试它,这个部分是完全正确的,它可以工作。字符串可以是大写和小写,没有标点符号。在

问题13b要求创建词典。关键是字符串中的单词(字符串有多个单词)。这个值就是每个单词中有多少个元音。问题是这样问的:如果单词至少有i个元音量,那么将它附加到字典(有数量元音的单词)这个函数有两个参数。第一个是没有标点符号的字符串。第二个参数表示单词必须附加到字典中的元音字母数。教授要我把13a函数称为算法的一部分。也就是说,问题13a的输出就是这个问题中关键(单个单词)的值。我在这个问题上遇到了麻烦,因为我无法让Python将13a(单词的元音数)的输出附加到字典键中。在

同样在下面的代码中,我还没有处理应该使用变量I的部分

这是我的代码:

    print("Question 13a")
    def vowelCount(s):
        vowels = 'aeiou'
        countVowels = 0
        for letter in s.lower():
            if letter in vowels:
                countVowels += 1
        print(countVowels)

    print("Question 13b")
    def manyVowels(t, i):
        my_string = t.split()
        my_dict = {}
        for word in my_string:
            number = vowelCount(word)
            my_dict[word].append(number)
        print(my_dict)    
    print(manyVowels('they are endowed by their creator with certain unalienable rights', 2))

如果你不能理解这个问题,下面是教授的指导:

问题13a(10分) 字母a,e,i,o和u是元音。没有其他字母是元音。 编写一个名为元音计数()的函数,该函数将字符串s作为参数,并返回 s包含的元音数。字符串s可以包含大写和小写字符。 例如,函数调用元音计数('Amendment')应该返回整数3,因为 字母“A”和“e”出现了3次。在

问题13b(10分) 编写一个名为manyVowels()的函数,它接受文本体t和整数i作为 参数。文本t只包含小写字母和空格。 manyVowels()应该返回一个字典,其中的键都是t中至少包含i的单词 元音。每个键对应的值是其中的元音数。全学分, manyPowers()必须调用问题11a中的助手函数元音计数()来确定 每个单词中元音的数目。例如,如果输入文本包含单词“hello”,则 “hello”应该是字典中的一个键,它的值应该是2,因为其中有2个元音 “你好”。 输入: 1t、 由小写字母和空格组成的文本 2i、 元音的阈值 Return:键值对的字典,其中的键是t中至少包含i的单词 元音和每个键的值是它包含的元音数。 例如,以下是正确的输出。在

text = 'they are endowed by their creator with certain unalienable rights' print(manyVowels(text, 3)) {'certain': 3, 'unalienable': 6, 'creator': 3, 'endowed': 3}


Tags: 函数字符串代码in文本参数字典my
3条回答

您的代码需要进行一些调整:

第一个函数应该返回一个值而不是打印它:

return (countVowels)

第二个功能是不正确地向字典中添加带有值的键。您应该使用:

^{pr2}$
def vowelCount(s):
  num_vowels=0
  for char in s:
    if char in "aeiouAEIOU":
      num_vowels = num_vowels+1
  return num_vowels

def manyVowels(text, i):
  words_with_many_vowels = dict()
  text_array = text.split()
  for word in text_array:
    if vowelCount(word) >= i:
       words_with_many_vowels[word] = vowelCount(word)
  return words_with_many_vowels

print(vowelCount('Amendment'))

text = 'they are endowed by their creator with certain unalienable rights'
print(manyVowels(text, 3))

输出:

^{pr2}$

试试看here!

添加条件以仅添加具有足够vovel的单词

def vowelCount(s):
    vowels = 'aeiou'
    countVowels = 0
    for letter in s.lower():
        if letter in vowels:
            countVowels += 1
    return countVowels

def manyVowels(t, i):
    my_string = t.split()
    my_dict = {}
    for word in my_string:
        number = vowelCount(word)
        if number >= i:
            my_dict[word] = number
    return my_dict 

my_dict[word] = numbervowelCount(word)的结果添加到字典中。但前提是vovel数至少为i。在

相关问题 更多 >

    热门问题