首页 > 解决方案 > 在某些单词周围的单词的正则表达式中包含“#”

问题描述

我想获得输出来确定某个单词附近的 3 个单词。对于此示例,单词将返回左侧的 3 个单词和右侧的 3 个单词围绕“to”。

import re 
sentence="#allows us to be free from the place"

key= "to"

left=[]
right=[]
m = re.search(r'((?:\w+\W+){,3})'+key+'\W+((?:\w+\W+){,3})',sentence)

if m:
    l = [ x.strip().split() for x in m.groups()]

    #l= two arrays of left and right
left, right = l[0], l[1]
print left, right

输出:

['allows', 'us'] ['be', 'free', 'from']

正如您从输出中看到的那样,不包括“#”符号。预期输出:

['#allows', 'us'] ['be', 'free', 'from']

注意:由于 "to" 周围最多只有 2 个单词,尽管正则表达式是 3 个单词,但它会返回两个单词

在某些情况下,关键可能不止一个词

似乎是什么问题,以及如何解决?谢谢

标签: pythonregexpython-2.7

解决方案


无需使用正则表达式执行此操作。您可以使用列表切片

sentence = '#allows us to be free from the place'
search_word = 'to'
context = 3

words = sentence.split()

try:
    word_index = words.index(search_word)
    start = max(0, word_index - context)
    stop = min(word_index + 1 + context, len(words))
    context_words = words[start:stop]
    print(context_words)
except ValueError:
    print('search_word not in the sentence')

印刷

['#allows', 'us', 'to', 'be', 'free', 'from']

如果您想要单独的“之前”和“之后”列表,请使用两个切片。


推荐阅读