python-3.x 按百分比计算字母和出现次数

rekjcdws  于 2023-03-20  发布在  Python
关注(0)|答案(2)|浏览(148)

我使用下面的函数来计算给定字符串中字母的出现次数:

def count(text):
    dicti = {}
    for sent in text:
        for letter in sent:
            if letter.isalpha():
                if letter in dicti.keys():
                    dicti[letter]+=1
                else:
                    dicti[letter] = 1
    print(dicti)

count("Hello World")

生成以下输出:

{'H': 1, 'e': 1, 'l': 3, 'o': 2, 'W': 1, 'r': 1, 'd': 1}

现在我想要得到这个结果,并且想要计算这些字母的出现百分比,以及没有出现在字符串中的字母,并且把它放在一个列表中:

[0, 0, 0, 0.1, 0.1, ..... ]
 a  b  c   d    e   ..... (do not list the letters)

我在上面的代码中添加了以下代码行:

print(dicti)
    list=[]
    list.insert(dicti)
    print(list(dicti))

我的目标是将输出放在列表中,然后应用百分比公式。
这是正确的方法吗?然而,我得到了一个错误:

TypeError: insert() takes exactly 2 arguments (1 given)
wljmcqd8

wljmcqd81#

你得到了一个正确的频率字典,但是还有一个更简单的方法(这在后面也会有好处),你可以使用Counter来减少一些(all?)逻辑:

from collections import Counter

counter = Counter(text)

如果要忽略空格,可以进行快速修改:

counter = Counter(c for c in text if c.isalpha())

这就是你所需要的频率。如果打印counter,你会得到:

Counter({'l': 3, 'o': 2, 'H': 1, 'e': 1, 'W': 1, 'r': 1, 'd': 1})

现在要创建一个你想要的所有字母的百分比列表,我们需要得到所有字母和总数。字母可以从string模块中获取,当使用Counter时,总数也变得很容易。就像counter.total()一样简单![1]
Counter的最后一个好处是你可以访问根本不存在的元素!它们默认返回0。

from string import ascii_letters
from collections import Counter

text = "Hello World"
counter = Counter(c for c in text if c.isalpha())

total = counter.total()
res = []
for letter in ascii_letters:
    res.append(counter[letter] / total)

print(res)

给出:

[0.0, 0.0, 0.0, 0.1, 0.1, ...

如果你想 “标准化” 小写/大写字母的计数,你可以将计数器改为c for c in text.lower()text.upper(),然后在循环中分别使用ascii_lowercaseascii_uppercase
[1]- total仅在Python 3.10中可用,对于早期版本,可以使用len(list(counter.elements()))sum(counter.values())

nhaq1z21

nhaq1z212#

1.设置一个字典,其中所有字母字符(包括小写和大写)的默认值均为0%。
1.我删除了额外的for循环,因为它是多余的,所以我们使用变量和增量来跟踪字母字符。
1.最后,我们循环键,并使用公式percentage = number of characters of type "x" divided by total number of characters设置百分比

def count(text):
    dicti = {i:0 for i in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"}
    total = 0
    for letter in text:
      if letter.isalpha():
          if letter in dicti.keys():
              dicti[letter]+=1
          else:
              dicti[letter] = 1
          total += 1

    for key in dicti.keys():
        dicti[key] = dicti[key]/total
    return dicti

print(count("Hello World")) # dictionary with all the key value pairs for the percentage occurrences
print(count("Hello World").values()) # list of percentages from a -> z, and A -> Z respectively

相关问题