在Python中,分别统计字典中大写和小写字母的数量

3

我试图完成以下练习:

考虑句子“Jim quickly realized that the beautiful gowns are expensive”。创建一个名为count_letters的字典,其中键由句子中每个唯一的字母组成,值由该字母在此句子中出现的次数组成。在字典中分别计算大写和小写字母。

以下是我的代码,我认为它正在按照练习要求执行,但出于某种原因它仍然显示我没有做对。有任何想法吗?

sentence = 'Jim quickly realized that the beautiful gowns are expensive'
count_letters = {}
cnt_lowercase = 0
cnt_uppercase = 0
#write your code here!
for c in sentence:
    if c.islower():
        if (c in count_letters) == False:
            count_letters[c]={c:sentence.count(c)}
            cnt_lowercase += 1
    if c.isupper():
        if (c in count_letters) == False:
            count_letters[c]={c:sentence.count(c)}
            cnt_uppercase += 1
print(str(cnt_lowercase))
print(str(cnt_uppercase))
print(count_letters)
11个回答

1
from collections import Counter


count_letters = Counter('Jim quickly realized that the beautiful gowns are expensive')
# this gives a dictionary of character -> count

# if you need to skip spaces/punctuations (you probably do), use this
count_letters = Counter(c for c in 'Jim quickly realized that the beautiful gowns are expensive' if c.isalpha())

1
你可以使用所谓的 列表推导式来实现这个。
 alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
 sentence = 'Jim quickly realized that the beautiful gowns are expensive'
 counts = dict([[letter, sentence.count(letter)] for letter in set(sentence) if letter in alphabet]) 

0
问题在于,count_letters是一个字典,其中键是字母,值是包含该字母计数的字典,在练习中要求计算:

由该句子中每个字母使用次数组成的值。

您的代码:

sentence = 'Jim quickly realized that the beautiful gowns are expensive'
count_letters = {}
cnt_lowercase = 0
cnt_uppercase = 0
for c in sentence:
    if c.islower():
        if (c in count_letters) == False:
            count_letters[c]={c:sentence.count(c)}
            cnt_lowercase += 1
    if c.isupper():
        if (c in count_letters) == False:
            count_letters[c]={c:sentence.count(c)}
            cnt_uppercase += 1
print(count_letters)

输出

{'u': {'u': 3}, 'g': {'g': 1}, 'q': {'q': 1}, 'l': {'l': 3}, 'o': {'o': 1}, 'm': {'m': 1}, 'f': {'f': 1}, 'k': {'k': 1}, 'z': {'z': 1}, 'w': {'w': 1}, 'a': {'a': 4}, 'n': {'n': 2}, 'c': {'c': 1}, 'y': {'y': 1}, 'r': {'r': 2}, 'b': {'b': 1}, 'h': {'h': 2}, 'd': {'d': 1}, 'e': {'e': 8}, 'i': {'i': 5}, 'v': {'v': 1}, 'p': {'p': 1}, 's': {'s': 2}, 'x': {'x': 1}, 'J': {'J': 1}, 't': {'t': 4}}

例如,'u' 的值为 {'u': 3}。您可以通过添加以下行来修复它:

count_letters = { k : v[k] for k, v in count_letters.items()}
print(count_letters)

输出 (带换行)

{'m': 1, 'c': 1, 'f': 1, 'b': 1, 'q': 1, 'd': 1, 'o': 1, 'g': 1, 'k': 1, 'r': 2, 'z': 1, 'v': 1, 'u': 3, 'l': 3, 'y': 1, 'p': 1, 's': 2, 'e': 8, 'x': 1, 'i': 5, 'w': 1, 'h': 2, 'n': 2, 'J': 1, 'a': 4, 't': 4}

解释

添加的这行代码被称为字典推导式。它等同于:

d = {}
for k, v in count_letters.items():
    d[k] = v[k]
count_letters = d

0

你的字典嵌套了其他不应该存在的字典

例如:

{'u': {'u': 3}}

应该只是

{'u': 3}

我简化了你的代码,现在应该可以工作了:

sentence = 'Jim quickly realized that the beautiful gowns are expensive'
count_letters = {}
cnt_lowercase = 0
cnt_uppercase = 0

for c in sentence:
    if (c in count_letters):
        count_letters[c] += 1
    else:
        count_letters[c] = 1

cnt_lowercase = len([i for i in count_letters.keys() if i.islower()])
cnt_uppercase = len([i for i in count_letters.keys() if i.isupper()])

print(count_letters)
print(cnt_lowercase)
print(cnt_uppercase)

0

你不应该使用一个字典的字典,而是直接返回字符出现次数的字典。这意味着当你输入 count_letters['J'] 时,你会得到1作为输出结果。

在你的代码中,当我输入 count_letters['J'] 时,我会得到 {'J': 1} 作为输出结果。

以下是我将如何编写此代码:

sentence = 'Jim quickly realized that the beautiful gowns are expensive'

count_letters = {}
cnt_lowercase = 0
cnt_uppercase = 0

# iterate over all chars in the sentence string
for char in sentence:
    # check if the char is lowercase
    if char.islower():
        cnt_lowercase += 1
    # check if the char is upper case
    elif char.isupper():
        cnt_uppercase += 1

    # count occurrence of each char in sentence string
    b = count_letters.get(char, 0)
    count_letters[char] = b + 1


# check the output
print(count_letters)

然后你会得到这个输出:

{'J': 1, 'i': 5, 'm': 1, ' ': 8, 'q': 1, 'u': 3, 'c': 1, 'k': 1, 'l': 3, 'y': 1, 'r': 2, 'e': 8, 'a': 4, 'z': 1, 'd': 1, 't': 4, 'h': 2, 'b': 1, 'f': 1, 'g': 1, 'o': 1, 'w': 1, 'n': 2, 's': 2, 'x': 1, 'p': 1, 'v': 1}

0
将缓存构建和计数逻辑委托给单独的函数:
   def build_cache(sentence):
        char_to_count_cache = {}
        for ch in sentence:
            if ch.isalnum():
                char_to_count_cache[ch] = char_to_count_cache.get(ch, 0) + 1

        return char_to_count_cache

    def get_upper_and_lower_counts(char_to_count_cache):
        num_lower_letters, num_upper_letters = 0, 0
        for k in char_to_count_cache:
            if k.islower():
                num_lower_letters += 1
            else:
                num_upper_letters += 1

        return num_lower_letters, num_upper_letters

驱动程序:

sentence = 'Jim quickly realized that the beautiful gowns are expensive'
char_to_count_cache = build_cache(sentence)
num_lower_letters, num_upper_letters = get_upper_and_lower_counts(char_to_count_cache)

total_letters = len(char_to_count_cache)

print total_letters
print num_lower_letters
print num_upper_letters

输出:

26 
25 
1 

能否告诉我为什么会被踩?如果有需要改进的地方,我很愿意去做... - LeKhan9

0
sentence = 'Jim quickly realized that the beautiful gowns are expensive'

count_upper = {}

count_lower = {}

count_letters = {}

# write your code here!

for c in sentence:

    if c.isupper():

        if (c in count_upper):

            count_upper[c] +=1

        else:

            count_upper[c] =1

    if c.islower():

        if (c in count_lower):

            count_lower[c] +=1

        else:

            count_lower[c] =1


count_letters = {**count_upper, **count_lower} ;

print(count_letters)

0
sentence = 'Jim quickly realized that the beautiful gowns are expensive'
count_letters = {}
for s in sentence:
    if (s.isupper()):# This checks upper case letters
        if (s not in count_letters.keys()):# This check whether the letter is in dict
            count_letters[s] = 1# if not in dict counts as the first
        else:
           count_letters[s] += 1 #if letter present it increments by 1
    else:
        if (s.islower()):
            if(s not in count_letters.keys()):
                count_letters[s] = 1
            else:
                count_letters[s] += 1
                
print(count_letters)

你也可以导入collections模块,然后在该模块中使用counter方法。 - guantai dickson
你的回答可以通过提供更多支持信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人可以确认你的答案是正确的。您可以在帮助中心找到有关如何编写良好答案的更多信息。 - Community

0

这是上述问题的解决方案。您可以根据自己的需求进行修改。

alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
sentence = 'Jim quickly realized that the beautiful gowns are expensive'
count_letters = dict()

for letter in sentence:
    if letter in alphabet:
        if letter in count_letters.keys():
            count_letters[letter] += 1
        else:
            count_letters[letter] = 1

print(list(count_letters.values())[2])
print(list(count_letters.values())[7])

0

这是我的建议,使用列表推导式

注意:在字典中要分别计算大写字母和小写字母。

sentence = 'Jim quickly realized that the beautiful gowns are expensive'

alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

count_letters_upper = ([[letter, sentence.count(letter)] for letter in set(sentence) if letter in alphabet if letter.isupper()])

count_letters_lower = ([[letter, sentence.count(letter)] for letter in set(sentence) if letter in alphabet if letter.islower()])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接