Skip to main content
 首页 » 编程设计

python之如何将特定单词封装在括号中

2025年04月02日15think

我是 Python 的新手,这是我的问题。我有一组词:

entities = ['blab', 'r1', 'zss'] 

我想检测它们并且我想封装它们以防万一

例如:

这个r1是关于zsse的 --> 这个[r1]是关于[zsse]的

同样,如果已经封装,我不会改变任何东西,例如,[ blablab r1 blabala ] 仍然是一样的。

我已经尝试了一些但它不起作用:

for s in sentences: 
    for e in entities: 
        if re.search(r"\[\[%s\]\]" % e, s): 
            pass 
        else: 
            s=s.replace(e,'[['+e+']]') 
 
        New_sentences.append(s) 

请您参考如下方法:

我就是这样做的。请注意,我使用了两个不同的正则表达式:

  • (\[.*?]) 识别括号内的区域
  • '({})'.format('|'.join(entities)) 匹配非括号区域内的任何实体。
import re 
 
brackets = re.compile(r'(\[.*?])') 
def rewrite(sentence, entities): 
    sentence = brackets.split(sentence) 
    entities = re.compile('({})'.format('|'.join(entities))) 
    for i, phrase in enumerate(sentence): 
        if not phrase.startswith('['): 
            sentence[i] = entities.sub(r'[\1]', phrase) 
    sentence = ''.join(sentence) 
    return sentence 
 
print rewrite('this r1 is about zsse', ['blab', 'r1', 'zss']) 
print rewrite('[ blablab r1 blabala ]', ['blab', 'r1', 'zss']) 

结果:

$ python x.py  
this [r1] is about [zss]e 
[ blablab r1 blabala ]