如何创建一个函数,该函数接受一个文本字符串并返回一个字典,其中包含某些已定义字符出现的次数(即使不存在)?

2024-05-23 14:57:14 发布

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

您好,我以前问过这个问题,我想调整我现在的代码。我想调整此代码,以便如果文本字符串中不存在字母,它仍会返回指定的值0

    count = {}
    for l in text.lower():
        if l in let:
            if l in count.keys():
                count[l] += 1
            else:
                count[l] = 1
    return count

它当前返回以下内容:

example = "Sample String"
print(func(example, "sao")
{'s': 2, 'a' : 1}

这将是我想要的输出

example = "Sample String"
print(func(example, "sao"))
{'s': 2, 'a' : 1, 'o' :0}

Tags: sample字符串代码textin文本forstring
3条回答

您可以使用Dict Comprehensionsstr.count

def count_letters(text, letters):
    lower_text = text.lower()
    return {c: lower_text.count(c) for c in letters}

print(count_letters("Sample String", "sao"))

result: {'s': 2, 'a': 1, 'o': 0}

如果您不介意使用专门为您的目的而设计的工具,那么以下方法可以:

from collections import Counter
def myfunc(inp, vals):
    c = Counter(inp)
    ​return {e: c[e] for e in vals}
s = 'Sample String'
print(myfunc(s, 'sao')

否则,可以在函数中显式设置所有缺少的值

def func(inp, vals):
    count = {e:0 for e in vals}
    for s in inp:
        if s in count:
            count[s] += 1
    return count
# create a function
def stringFunc(string, letters):
    # convert string of letters to a list of letters
    letter_list = list(letters)
    # dictionary comprehension to count the number of times a letter is in the string
    d = {letter: string.lower().count(letter) for letter in letter_list}
    return d

stringFunc('Hello World', 'lohdx')


# {'l': 3, 'o': 2, 'h': 1, 'd': 1, 'x': 0}

相关问题 更多 >