Python处理字符串中的特定字符

2024-09-26 17:43:57 发布

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

def value(x):

s = "Since 2012, Champion Data has boxed players in five categories, ranging from 'elite' to 'poor', based on a complicated formula assessing their most recent form. Players who have yet to debut, played only sparingly or are returning from long-term injuries (less than 10 games in two seasons) are placed in a sixth category named, appropriately, '?'. "

目的是将文本中参数x不同出现次数的索引相加,除以出现次数,再除以文本长度。 我试了无数次,但似乎还没弄明白。你知道吗


Tags: toinfrom文本datavaluedef次数
3条回答

您可以使用枚举获得如下索引:

indices = [i for i, j in enumerate(s) if x == j]

您可以找到索引之和为sum(indices),出现次数为len(indices),字符串长度为len(s)

最终结果可以计算为

return sum(indices)/(len(indices)*len(s))

这是您的密码:

import re

def count(sentence, st):
    indicies = [i.start() for i in re.finditer(st, sentence)]
    indicies_sum = sum(indicies)
    number_of_occurrences = len(indicies)
    text_len = len(sentence)
    return float(indicies_sum)/(number_of_occurrences*text_len)
def count(s, x):
    lx = len(x)
    slices = s.split(x)
    positions = [len(slice) + lx * n
                 for n, slice in enumerate(slices)]
    return float(sum(positions)) / len(s) / len(slices - 1)

相关问题 更多 >

    热门问题