python - 在某些单词周围的单词的正则表达式中包含“#”
问题描述
我想获得输出来确定某个单词附近的 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 个单词,但它会返回两个单词
在某些情况下,关键可能不止一个词
似乎是什么问题,以及如何解决?谢谢
解决方案
无需使用正则表达式执行此操作。您可以使用列表切片。
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']
如果您想要单独的“之前”和“之后”列表,请使用两个切片。
推荐阅读
- angular - 带有键盘导航的 Angular Material Table - 监听所有 keydown 事件,除了来自 Overlay 组件的事件
- python - 使用 SHAP 值来解释 LogisticRegression 分类
- angular - 如何为 Ionic 和 Angular 的 ui 库配置故事书
- python - 检查列表中整个确切字符串的输入
- javascript - 从 Javascript 数组中过滤偶数元素
- javascript - 通过 Flask 到 Json 到 D3 的数据帧
- loops - 用于了解给定文本文件有多少考试的 AWK 脚本
- sql - 从雪花中的字符串中删除重音
- angular - 登录后,MSAL (Angular) 不会重定向,但 URL 有值
- css - 使用 ::before 或 ::after 伪元素来维护动画元素的区域?