使用Python从字符串中查找所有重复字符
给出一个字符串。我们的任务是找到给定字符串中出现频率大于1的那些字符。
例如,我们可以看到字符串“ Hello World。让我们学习Python”,这样算法就会找到那些出现多次的字母。在这种情况下,输出将如下所示:
e : 3l : 4
o , 3)
<space> : 4
r : 2
t : 2
n : 2
为了解决这个问题,我们使用Python集合。从集合中,我们可以获得Counter()
方法。该Counter()
方法用于计算哈希表对象。在这种情况下,它将字符从文本中分离出来,并将每个字符作为字典的键,而字符数就是这些键的值。
算法
Step 1: Find the key-value pair from the string, where each character is key and character counts are the values.Step 2: For each key, check whether the value is greater than one or not.
Step 3: If it is greater than one then, it is duplicate, so mark it. Otherwise, ignore the character
范例程式码
from collections import Counterdefcalc_char_freq(string):
freq_count = Counter(string) # get dictionary with letters as key and frequency as value
for key in freq_count.keys():
if freq_count.get(key) > 1: # for all different keys, list the letters and frequencies
print("(" + key + ", " + str(freq_count.get(key)) + ")")
myStr = 'Hello World. Let’s learn Python'
calc_char_freq(myStr)
输出结果
(e, 3)(l, 4)
(o, 3)
( , 4)
(r, 2)
(t, 2)
(n, 2)
以上是 使用Python从字符串中查找所有重复字符 的全部内容, 来源链接: utcz.com/z/353477.html