我如何在Python中列出元组中元音的出现,然后根据元音数将其附加到字典?
这是我目前的尝试:
def vowelCount(input1):
d = {'half vowels': None,
'mostly consonant': None, 'mostly vowels': None}
vowels = 'aeiou'
con = 0
for word in input1:
print(word, len(word))
for vowel in vowels:
if vowel in word:
print(word.count(vowel))
# FIXME: I can't figure out how to
# sum up the occurrences
#if (word.count(vowel)) < len(word):
# print(word)
以下是对我的期望的描述:
its 3
1
a 1
1
death 5
1
1
trap 4
1
its 3
1
a 1
1
suicide 7
1
2
1
rap 3
1
we 2
1
gotta 5
1
1
get 3
1
out 3
1
1
while 5
1
1
were 4
2
young 5
1
1
答案 0 :(得分:2)
我想我理解你的问题,但我并非百分百肯定,如果这不是你正在寻找的,那么道歉。元音数量有限,因此您可以通过定义元音并保持活动计数来确定有多少元音。
def vowel_count(s):
"""
@param s is a string representing the contents of the list
"""
vowels = ['a', 'e', 'i', 'o', 'u']
counts = {}
for v in vowels:
counts[v] = 0
for c in s:
if c in vowels:
counts[c] += 1
return counts
这些方面的东西?
答案 1 :(得分:1)
根据你的代码,我就是你想要的。对于每个单词,将vowelcount重置为0并继续查找单词中的元音数量。根据此计数,构建您的字典D.
def vowelCount(input1):
d={'half vowels': [], 'mostly constant':[], 'mostlyVowels':[]}
vowels='aeiou'
for word in input1:
print(word, len(word))
vowelcount = 0
for vowel in vowels:
if vowel in word:
vowelcount += word.count(vowel)
if vowelcount == len(word)/2:
d["half vowels"].append(word)
elif vowelcount < len(word)/2:
d["mostly constant"].append (word)
else:
d["mostlyVowels"].append(word)
return d
然而,这段代码很乱。尝试将这些功能分离为独立的可测试功能:
def vowelcount(word):
# ...
return number of vowels in word
def constructSummary(listOfWords):
d = { }
for word in words:
count = vowelcount(word)
# .. If else ladder based on count
# construct d based on count
return d
答案 2 :(得分:1)
以您的代码为基础,您只需修改一些内容,如下所述。结果是你的isLoggedIn
字典,所有单词都正确排序。这个版本将一个句子作为输入,在空格处分成一个列表:
<ul class="nav navbar-nav navbar-right" ng-controller="loginController">
<li class="dropdown">
<a href="#" class="dropdown-toggle"
data-toggle="dropdown"
ng-show="isLoggedIn"
ng-click="logout()">
<b>Logout</b></a>
<a href="#" class="dropdown-toggle"
data-toggle="dropdown"
ng-show="!isLoggedIn">
<b>Login</b> <span class="caret"></span>
</a>
</li>
</ul>
此代码将提供以下结果:
d