我需要知道一个字符显示了多少次,并将结果保存在字典中。例如:CCD_ 1表示";e";显示8次;s";显示7次。我必须使大小写值相同。
我设法弄清楚每个角色显示了多少次。我很难把大写字母和小写字母放在一起而不是分开。
counting_symbols = {}
for letter in "Cryptography is the practice and study of techniques"
" for secure communication in the presence of third parties"
" called adversaries. More generally, cryptography is about"
" constructing and analyzing protocols that prevent third"
" parties or the public from reading private messages; various "
"aspects in information security such as data confidentiality, "
"data integrity, authentication, and non-repudiation are central "
"to modern cryptography. Modern cryptography exists at the"
" intersection of the disciplines of mathematics, computer science, "
"electrical engineering, communication science, and physics. Applications "
"of cryptography include electronic commerce, chip-based payment cards, "
"digital currencies, computer passwords, and military communications.":
counting_symbols[letter] = counting_symbols.get(letter, 0) + 1
print(counting_symbols)
这使大写字母和小写字母分开。有人能帮忙让他们联合起来吗?
您只需要添加一行代码即可将字母转换为小写:
counting_symbols = {}
for letter in "Cryptography is the practice and study of techniques"
" for secure communication in the presence of third parties"
" called adversaries. More generally, cryptography is about"
" constructing and analyzing protocols that prevent third"
" parties or the public from reading private messages; various "
"aspects in information security such as data confidentiality, "
"data integrity, authentication, and non-repudiation are central "
"to modern cryptography. Modern cryptography exists at the"
" intersection of the disciplines of mathematics, computer science, "
"electrical engineering, communication science, and physics. Applications "
"of cryptography include electronic commerce, chip-based payment cards, "
"digital currencies, computer passwords, and military communications.":
letter = str.lower(letter)
counting_symbols[letter] = counting_symbols.get(letter, 0) + 1
print(counting_symbols)
您可以使用lower((函数降低所有字符,并将其保存到另一个变量中。
使用集合库中的Counter类也是一种很好的做法。Counter对象自动计算字符串中的字符数或列表中的字符串数,并将数据保存在字典中。
text = "Cryptography is the practice and study of techniques"
lower_chars = text.lower()
from collections import Counter
counter = Counter(lower_chars)
print(counter)
计算它们的方式可以更具体。只是给你一个伪代码的例子:
if(letter == ('S' or 's')):
num_s = num_s+1
例如,在函数中,您可以为每个字母复制并粘贴这一行。最后,你可以返回这些数字。我希望你明白我的算法的要点。你可以用很多方法来实现它,我的算法只是非常非常具体。