替换字符串列表中的字符串

时间:2016-10-16 06:47:51

标签: python string

我的代码有问题。在此示例中,它应打印出The Wind in the Willows,但它会打印 The Wind In The Willows 。我认为问题是替换功能不执行。我不知道这段代码有什么问题。请帮忙。

PS。这个函数的基本思想是返回带有异常(minor_words)的标题相似字符串。 Minor_words在标题中应为小写(尽管如果minor_wordstitle中的第一个单词,则为{<1}})

def title_case(title, minor_words):
    exc = [x for x in title.lower().split() if x in minor_words.lower().split()]
    for string in exc:
        if title.split().index(string) == 0:
            title = title.title()
        else:
            title = title.title().replace(string, string.lower())
    return title


print (title_case('THE WIND IN THE WILLOWS', 'The In'))

3 个答案:

答案 0 :(得分:2)

def title_case(title, minor_words):
    # lowercase minor_words and make a set for quicker lookups
    minor_set = set(i for i in minor_words.lower().split())
    # tokenize the title by lowercasing
    tokens = title.lower().split()
    # create a new title by capitalizing words that dont belong to minor_set
    new_title = ' '.join(i if i in minor_set else i.capitalize() for i in tokens)
    # Finally return the capitalized title.
    if len(new_title) > 1:
        return new_title[0].upper() + new_title[1:]
    else:
        # Since its just one char, just uppercase it and return it
        return new_title.upper()

输出:

>>> print (title_case('THE WIND IN THE WILLOWS', 'The In'))
The Wind in the Willows

答案 1 :(得分:1)

由于您在循环中分配给title,因此您获得的title值与上次循环时分配给它的值相同。

我以不同的方式做到了这一点。我遍历标题中的所有单词(不仅仅是排除项)和标题大小写未被排除的单词。

def title_case(title, minor_words):
    """Title case, excluding minor words, but including the first 
    word"""

    exclusions = minor_words.lower().split()
    words = title.split()

    # Loop over the words, replace each word with either the title
    # case (for first word and words not in the exclusions list) 
    # or the lower case (for excluded words)
    for i, word in enumerate(words):
        if i == 0 or word.lower() not in exclusions:
            words[i] = words[i].title()
        else:
            words[i] = words[i].lower()

    title = " ".join(words)
    return title


print (title_case('THE WIND IN THE WILLOWS', 'The In'))

答案 2 :(得分:0)

for x in minor_words.split():
        title = title.replace(x,x.lower())

我对你到底要做什么感到困惑(对我来说已经很晚了,所以我无法思考),但这会取代title中所有{{1}的单词使用小写副本。首字母可以用minor_words

完成