Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将特定单词封装在括号中?_Python_Regex - Fatal编程技术网

Python 如何将特定单词封装在括号中?

Python 如何将特定单词封装在括号中?,python,regex,Python,Regex,我是Python的新手,这是我的问题。我有一组词: entities = ['blab', 'r1', 'zss'] 我想检测它们,我想封装它们,以防没有 例如: 这个r1是关于zsse的-->这个[r1]是关于[zsse] 同样,如果已经封装了,我不会更改任何内容,例如,[blablab r1 blabala]仍将保持不变 我尝试了一些东西,但不起作用: for s in sentences: for e in entities: if re.search(r"\[\

我是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)
您可以尝试以下方法:

In [48]: eentities = ['blab', 'r1', 'zss']

In [49]: s = 'this r1 is about zsse'

In [50]: import re

In [52]: rs = re.compile('|'.join(eentities))

In [60]: sl = list()

for se in s.split():
    if(rs.match(se)):
        sl.append('[{0}]'.format(se))
    else:
        sl.append(se)

In [62]: sl
Out[62]: ['this', '[r1]', 'is', 'about', '[zsse]']

In [63]: ' '.join(sl)
Out[63]: 'this [r1] is about [zsse]'

如果您只关心
实体
是否是句子中单词的子字符串,那么就不必使用正则表达式

sentences = ['this r1 is about zsse', '[blablab r1 blabala]']
entities = ['blab', 'r1', 'zss']
new_sentences = []

for sentence in sentences:
    if sentence.startswith('[') and sentence.endswith(']'):
        new_sentences.append(sentence)
        continue

    sentence = sentence.split(' ')

    for index, word in enumerate(sentence):
        for entity in entities:
            if entity in word:
                sentence[index] = '[{w}]'.format(w=word)

    new_sentences.append(' '.join(sentence))

print new_sentences
>>> ['this [r1] is about [zsse]', '[blablab r1 blabala]']
请尝试以下代码:

import re

entities = ['blab', 'r1', 'zss']
sentences = ['this r1 is about zsse', 'this [r1] is about [zss]e']
new_sentences = []

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)

print(new_sentences)
# >>> ['this [r1] is about [zss]e', 'this [r1] is about [zss]e']

您的代码唯一的问题是
新句子。append
缩进太远<代码>新的句子正在
中。每次循环通过
实体
时追加
。因此,对于每个
句子
,有3个
新句子


你似乎把一切都变成了
[[]]
\[\[\]\]
而不是
[\[\]
\[\]

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

  • (\[.*?])
    标识括号内已经有哪些区域
  • “({})”格式(“|”.join(entities))
    匹配非括号区域内的任何实体
结果:

$python x.py
这[r1]是关于[zss]e的
[blablab r1 blabala]

您需要扩展正则表达式,以便在单词前后允许零个或多个字符。它可以是任何东西,除了……您希望单词立即用
[]
括起来,还是这些括号中可能有更多的单词。其次,对于像
[ad cd[ad]]ad
这样的嵌套括号,您想将
ad
括起来吗?在您的示例中,列表中的
zss
zsse
有什么关系?这是打字错误,还是你真的想做前缀匹配?在你输入的句子中,
[
是否嵌套过?它们是否会不平衡?OP声称他/她的解决方案不起作用!并且在提供的解决方案中,此解决方案使用了单个for循环而不是多个循环。是的,因此,只需发布一大部分全新的代码(甚至没有解释它),为什么不分析他们的代码,告诉他们做错了什么,以及如何纠正。
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'])