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

2024-06-09 23:30:51 发布

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

我想创建一个函数,该函数将高亮显示给定单词的每一次出现

  • 我已经成功地使我的功能工作,但只有当我们给它一个字来强调
  • 如果我们给它一个以上的单词,该函数将打印多个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"]))

这是程序打印的内容:

Have a NICE day, you NICE person!!

Shhh, don't be so LOUD!Shhh, don't BE so loud!

Automating with Python is FUNAUTOMATING with Python is fun

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


Tags: 函数lensoiswith单词sentencefinal
3条回答

使用递归:-

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

我认为如果你把外环变成字符串而不是单词,那就容易多了。下面是一个选项

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"]))

您可以简单地使用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

希望有帮助:)

相关问题 更多 >