有没有一种简单的方法来计算一个单词中重复字符的数量?

2024-10-03 09:10:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道一个单词里有多少个字符重复出现。重复必须是连续的。在

例如,带有输入"loooooveee"的方法应该返回6(4倍于“o”,2倍于“e”)。在

我正在尝试实现字符串级函数,我可以这样做,但是,有没有一个简单的方法来做到这一点?正则表达式,还是其他什么?在


Tags: 方法函数字符串单词个字符loooooveee
3条回答

原始问题:order of repetition does not matter

你可以用字母总数减去唯一字母的数目。^应用于字符串的{a1}将返回一个唯一的字母集合。在

x = "loooooveee"
res = len(x) - len(set(x))  # 6

或者可以使用^{},从每个值中减去1,然后sum

^{pr2}$

新问题:repetitions must be sequential

可以使用^{}对顺序相同的字符进行分组:

from itertools import groupby

g = groupby("aooooaooaoo")
res = sum(sum(1 for _ in j) - 1 for i, j in g)  # 5

要避免嵌套的sum调用,可以使用^{}

from itertools import groupby, islice

g = groupby("aooooaooaoo")
res = sum(1 for _, j in g for _ in islice(j, 1, None))  # 5

试试这个:

word=input('something:')

sum = 0

chars=set(list(word)) #get the set of unique characters

for item in chars: #iterate over the set and output the count for each item
    if word.count(char)>1:
       sum+=word.count(char)
    print('{}|{}'.format(item,str(word.count(char)))

print('Total:'+str(sum))

编辑:

增加了总重复次数

如果需要,可以使用正则表达式:

import re

rx = re.compile(r'(\w)\1+')

repeating = sum(x[1] - x[0] - 1
                for m in rx.finditer("loooooveee")
                for x in [m.span()])
print(repeating)

这将正确生成6,并使用.span()函数。


表达式是 ^{pr2}$

它捕获一个单词字符(其中一个是a-zA-Z0-9_),并尽可能频繁地重复它。
有关重复模式,请参见a demo on regex101.com


如果要匹配任何字符(即不仅仅是单词字符),请将表达式更改为:
(.)\1+

another demo on regex101.com。在

相关问题 更多 >