如何突出显示字符串中的单词[Python]

时间:2020-06-22 15:38:45

标签: python string highlight word

我想创建一个函数,该函数将在每次出现给定单词时突出显示[.upper()]。

  • 仅当我们给它一个单词突出显示时,我才能使我的函数正常工作。
  • 如果我们给它超过1个单词,该函数将打印多个突出显示1个单词的句子。

我知道为什么会这样做,但是我不知道有什么其他办法可以使它遥不可及,因此您的帮助会真正帮助我! ? 我尝试将不同的最终结果保存到列表中,但是我应该如何将它们连接到1个最后的最终句子中?

def highlight_words(sentence, words):
    final = ""
    k = 0
    for j in range(len(words)):
        for i in range(len(sentence)):
            if k != 0:
                k -= 1
                continue
            changed = ""
            if sentence.lower().startswith(words[j].lower(), i):
                changed = sentence[i:i+len(words[j])].upper()
                final += changed
                k = len(words[j]) - 1
            else:
                final += sentence[i]
    return final

print(highlight_words("Have a nIcE day, you Nice person!!", ["nice"]))
print(highlight_words("Shhh, don't be so loud!", ["loud", "Be"]))
print(highlight_words("Automating with Python is fun", ["fun", "auTomaTiNG"]))

这是程序打印的内容:

祝您有个美好的一天!

嘘,别那么大声!嘘,别那么大声!

使用Python自动化很有趣用Python进行自动化

如果您在解决方案中不使用任何导入的库,我将不胜感激!预先感谢!

4 个答案:

答案 0 :(得分:0)

您可以像这样简单地通过使用splitjoin来做到这一点:

def highlight_words(sentence, words):
    for word in words:
        if(word.lower() in sentence.lower()):
            sentence = sentence.split(word)
            sentence = word.upper().join(sentence)
    return sentence

希望它会有所帮助:)

答案 1 :(得分:0)

我认为,如果将外循环设为字符串而不是单词,则容易得多。下面是一个选项。

def highlight_words(sentence, words):
    for i in range(len(sentence)):
        for j in range(len(words)):    
            if sentence.lower().startswith(words[j].lower(), i):
                sentence = sentence[:i] + sentence[i:i+len(words[j])].upper() + sentence[i+len(words[j]):]
    return sentence

print(highlight_words("Have a nIcE day, you Nice person!!", ["nice"]))
print(highlight_words("Shhh, don't be so loud!", ["loud", "Be"]))
print(highlight_words("Automating with Python is fun", ["fun", "auTomaTiNG"]))

答案 2 :(得分:0)

使用递归:-

def highlight_words(sentence, words):
    for word in words:
        pos = sentence.lower().find(word.lower())
        sentence = sentence if pos < 0 else sentence[0:pos] + word.upper() + highlight_words(
            sentence[pos + len(word):], [word])
    return sentence

答案 3 :(得分:0)

这是我的答案,在 Coursera 测验中效果很好。

def highlight_word(sentence, word):
    ans=""
    parts=sentence.split()#parts = splitted sentence
    for part in parts:
        Cpart=part.strip("!,")#Cpart means Clean part after stripping the ! ans , etc
        if Cpart==word:#if our clean part is equal to word provided
            part=part.upper()#then convert the part to Upper Case
        ans = ans+" "+part#keep adding the parts in ans string
    return(ans)

print(highlight_word("Have a nice day", "nice"))
print(highlight_word("Shhh, don't be so loud!", "loud"))
print(highlight_word("Automating with Python is fun", "fun"))