I want to capitalize keywords in a list of strings except for keywords that are in quote.
let's say you have
list1 = ["I like bananas", "he likes 'bananas' and apples", "we like bananas and apples"]
list2 = ["bananas", "apples"]
the output I'd want is
>>> ["I like BANANAS", "he likes 'bananas' and APPLES", "we like BANANAS and APPLES"]
CodePudding user response:
You can use regular expression to check if the phrase in list2
is surrounded by quotes or not:
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'"
You can create function to replace all patterns in 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']
CodePudding user response:
This is what I have
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)