我需要知道一个字符显示了多少次,并将结果保存在字典中。例如:{"e": 8, "s": 7}的意思是"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)这使大写字母和小写字母分开。有人能帮忙让他们联合起来吗?
发布于 2020-12-28 18:58:24
您只需添加1行代码即可将字母转换为小写:
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)发布于 2020-12-28 19:03:50
可以使用lower()函数降低所有字符,并将其保存到另一个变量中。
使用集合库中的计数器类也是一个很好的实践。计数器对象会自动计数字符串中的字符或列表中的字符串,并将数据保存在字典中。
text = "Cryptography is the practice and study of techniques"
lower_chars = text.lower()
from collections import Counter
counter = Counter(lower_chars)
print(counter)发布于 2020-12-28 18:56:29
你计算它们的方式可以更具体。为了给您提供一个伪代码示例:
if(letter == ('S' or 's')):
num_s = num_s+1您只需复制和粘贴这一行的每一个字母,例如,在一个函数。最后,你可以返回这些数字。我希望你能明白我算法的要点。您可以通过多种方式实现它,我的算法非常具体。
https://stackoverflow.com/questions/65482502
复制相似问题