Reputation: 45
So I have this dictionary,
word_counts = {'Two':2, 'one':3, 'Forks.':1, 'knife.':2,
'glasses.':2, 'plate.':1, 'Naptkin.':1, 'his':2}
And i need to compute how to how many are capitalized and non-capitalized. I know I need to do this by getting the keys of the dictionary and loop through them all, but I'm having trouble. Please help. Thank you!
Tried to use counter variables with for loops and isupper() and islower() but its not working. If you haver better ways please let me know!
#What ive done so far
word_counts = {'Two':2, 'one':3, 'Forks.':1, 'knife.':2,
'glasses.':2, 'plate.':1, 'Naptkin.':1, 'his':2}
for word, occurence in words:
upper_counter = 0
lower_counter = 0
for word in word_counts.items():
if word.isupper():
upper_counter += 1
elif word_islower():
lower_counter += 1
Upvotes: 3
Views: 168
Reputation: 1
Here's a simplest approach using 1. list comprehension, 2. string formatting.
word_counts = {'Two':2, 'one':3, 'Forks.':1, 'knife.':2,
'glasses.':2, 'plate.':1, 'Naptkin.':1, 'his':2}
Create lists of caps and non-caps words.
caps = [i for i in word_counts.keys() if i[0].isupper()]
non_caps = [i for i in word_counts.keys() if i not in caps]
print("There are {} capitalized words.
They are:{}{}".format(len(caps), "\n", caps))
print("There are {} non-capitalized words.
They are:{}{}".format(len(non_caps), "\n", non_caps))
Upvotes: 0
Reputation:
Your purpose is counting all uppercase from keys, or count number of keys that contain uppercase.
Count all uppercase from keys:
all_keys = ''.join(list(word_counts.keys()))
count = len([w for w in all_keys if w.isupper()])
Count all words contain upper
count = len([word for word in word_couhnts.keys() if
any([w for w in word if w.isupper()])])
Upvotes: 0
Reputation: 32244
# The counters should be initialised before the loop
upper_counter = 0
lower_counter = 0
for word in word_counts: # Looping over a dictionary gives the keys
if word[0].isupper(): # Just have to check if the first character is upper case
upper_counter += 1
else:
lower_counter += 1
Upvotes: 2
Reputation: 71461
You can use re
:
import re
cap, non_cap = 0, 0
word_counts = {'Two':2, 'one':3, 'Forks.':1, 'knife.':2, 'glasses.':2, 'plate.':1, 'Naptkin.':1, 'his':2}
for a in word_counts:
if re.findall('^[A-Z]\w+', a):
cap += 1
else:
non_cap += 1
Output:
3 #cap
5 #non_cap
Upvotes: 0