将字符串中的单词大写,引号中的单词除外

Capitalize words in string except for ones in quote

我想将字符串列表中的关键字大写,引号中的关键字除外。

假设你有

list1 = ["I like bananas", "he likes 'bananas' and apples", "we like bananas and apples"]
list2 = ["bananas", "apples"]

我想要的输出是

>>> ["I like BANANAS", "he likes 'bananas' and APPLES", "we like BANANAS and APPLES"]

您可以使用正则表达式来检查 list2 中的短语是否被引号括起来:

import re

In [ ]: re.sub(rf"(?<!')\bbananas\b(?!')", "BANANAS", "I like bananas")
Out[ ]: 'I like BANANAS'

In [ ]: re.sub(rf"(?<!')\bbananas\b(?!')", "BANANAS", "I like 'bananas'")
Out[ ]: "I like 'bananas'"

您可以创建函数来替换 list2 中的所有模式:

def capitalize(s, pats):
     for pat in pats:
         s = re.sub(rf"(?<!')\b{pat}\b(?!')", pat.upper(), s)
     return s

In [ ]: [capitalize(s, list2) for s in list1]
Out[ ]:
['I like BANANAS',
 "he likes 'bananas' and APPLES",
 'we like BANANAS and APPLES']

这就是我的

for sentence in list1:
    for keyword in list2:
        if keyword in sentence:
            start_index = sentence.index(keyword)
            if not start_index != 0 or not sentence[start_index-1] == "'":
                sentence = sentence[:start_index] + keyword.upper() + sentence[start_index + len(keyword):]
    print(sentence)