0

I am totally new to regex. Now I have a string and a keyword dealing with adding Chinese brackets "" and "" before and after the two keywords in my string (no matter what between the two keywords)

In case my bad explanation, my current code is like below:

keyword = 'keyword'
def add_brackels(string):
    brackel_regex = re.compile(r"%s.*%s" % (keyword,keyword))
    
    final = re.sub(brackel_regex, lambda p: '「'+ p.group(0) + '」', string)
    return final

(keyword depends on different input cases which I have already defined)

For example, here is my input:

# keyword = 'pen'
I like pencil. And I don't like pen. Please give me a pen.

# keyword = '水果'
水果水果水果
水果. 水果    愛吃水果;
喝水果然健康,吃水果也是

# keyword = 'abc'
abcabcabcabc
abc. Abcabcabc
abc. Abcabcabcabc

And I want to get the outputs below:

# keyword = 'pen'
I like 「pencil. And I don't like pen」. Please give me a pen.

# keyword = '水果'
「水果水果」水果
「水果. 水果」    愛吃水果;
喝「水果然健康,吃水果」也是

# keyword = 'abc' 
「abcabc」「abcabc」
「abc. Abcabc」abc
「abc. Abcabc」「abcabc」

But using my current code, it became like this:

# keyword = 'pen'
I like 「pencil. And I don't like pen. Please give me a pen」.

# keyword = '水果'
「水果水果水果」
「水果. 水果    愛吃水果」;
喝「水果然健康,吃水果」也是 <-

# keyword = 'abc'
「abcabcabcabc」
「abc. Abcabcabc」
「abc. Abcabcabcabc」

Please mind the only arrow after the 4th line in my output. If my code is all wrong, it may be like other strings that locate brackets in the very beginning and the end, but eventually the 4th line works well.

I guess it may be something wrong with the punctuations like ., ;, : and ; and had searched for a bit but didn't find the answer I want Also, the keyword amount my code catches is over the ones I defines in r"%s.*%s" % (keyword,keyword)

Could somebody help tell me where am I doing wrong?

Hazel Lin
  • 11
  • 3

0 Answers0