Python - 使用字符串中的特定字符

时间:2015-04-02 12:39:56

标签: 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的不同出现次数的索引,并除以出现次数,并进一步除以文本的长度。 我已经无休止地尝试过,但似乎无法弄明白。

3 个答案:

答案 0 :(得分: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))

答案 1 :(得分:3)

这是你的代码:

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)

答案 2 :(得分:1)

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)