我试图从字符串中删除特定数量的重复字母并显示字符串。 例如,我有一个像" sdfgsd sdfd jkhj dfg sdf"我想从这个字符串中删除3次以上的重复字母并再次显示。我试图用python做到这一点 我怎样才能做到这一点。这是我的代码:
chars = "abcdefghijklmnopqrstuvwxyz"
check_string = "aanbg sdfsd futy asdf sdferg gyıuy"
for char in chars:
count = check_string.count(char)
//3 and more than 3 times repeated letters removing from string
if count >= 3:
remove (char, count)
print("check_string")
答案 0 :(得分:1)
这应该有效:
>>> from collections import Counter
>>> check_string = "aanbg sdfsd futy asdf sdferg gyıuy"
>>> letter_occurrances = Counter(check_string).items()
>>> letter_occurrances
dict_items([('a', 3), ('n', 1), ('b', 1), ('g', 3), (' ', 5), ('s', 4), ('d', 4), ('f', 4), ('u', 2), ('t', 1), ('y', 3), ('e', 1), ('r', 1), ('ı', 1)])
>>> for key, value in letter_occurrances:
if value>=3 and key!=' ':
check_string = check_string.replace(key, '')
>>> check_string
'nb ut er ıu'
如果您想自己实施letter_occurrances
:
>>> from collections import defaultdict
>>> check_string = "aanbg sdfsd futy asdf sdferg gyıuy"
>>> letter_occurrances = defaultdict(int)
>>> for letter in check_string:
letter_occurrances[letter] += 1
>>> letter_occurrances
defaultdict(<class 'int'>, {'a': 3, 'n': 1, 'b': 1, 'g': 3, ' ': 5, 's': 4, 'd': 4, 'f': 4, 'u': 2, 't': 1, 'y': 3, 'e': 1, 'r': 1, 'ı': 1})
>>> for key, value in letter_occurrances:
if value>=3 and key!=' ':
check_string = check_string.replace(key, '')
>>> check_string
'nb ut er ıu'