我使用下面的函数来计算给定字符串中字母的出现次数:
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)
2条答案
按热度按时间wljmcqd81#
你得到了一个正确的频率字典,但是还有一个更简单的方法(这在后面也会有好处),你可以使用
Counter
来减少一些(all?)逻辑:如果要忽略空格,可以进行快速修改:
这就是你所需要的频率。如果打印
counter
,你会得到:现在要创建一个你想要的所有字母的百分比列表,我们需要得到所有字母和总数。字母可以从
string
模块中获取,当使用Counter
时,总数也变得很容易。就像counter.total()
一样简单![1]Counter
的最后一个好处是你可以访问根本不存在的元素!它们默认返回0。给出:
如果你想 “标准化” 小写/大写字母的计数,你可以将计数器改为
c for c in text.lower()
或text.upper()
,然后在循环中分别使用ascii_lowercase
或ascii_uppercase
。[1]-
total
仅在Python 3.10中可用,对于早期版本,可以使用len(list(counter.elements()))
或sum(counter.values())
。nhaq1z212#
1.设置一个字典,其中所有字母字符(包括小写和大写)的默认值均为0%。
1.我删除了额外的for循环,因为它是多余的,所以我们使用变量和增量来跟踪字母字符。
1.最后,我们循环键,并使用公式
percentage = number of characters of type "x" divided by total number of characters
设置百分比