Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/vim/5.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 - Fatal编程技术网

如何在Python中从字符串的索引开始获取整个单词

如何在Python中从字符串的索引开始获取整个单词,python,Python,我有点像: import re text = 'hi this is john my name is john im bad boy' target = 'is john' target = target.replace(' ', '[\s\n]*') target = re.compile(r'\b%s' % target, flags=re.I | re.X) indices = [m.start() for m in re.finditer(target, text)] 然后我想在索引中

我有点像:

import re
text = 'hi this is john my name is john im bad boy'
target = 'is john'
target = target.replace(' ', '[\s\n]*')
target = re.compile(r'\b%s' % target, flags=re.I | re.X)
indices = [m.start() for m in re.finditer(target, text)]

然后我想在索引中查找每个出现的前后词(即“this”、“my”和“name”、“im”)。但是,我希望避免使用正则表达式直接查找单词,因为搜索更大的文件时速度太慢,而且如果我希望在每次出现的目标文件的每一侧查找n>1个单词,则查找速度太慢。所以我有索引,我想得到索引中单词前后的单词。

split
搜索短语中的字符串。然后从产生的句子片段中提取“边界”词:

frag_list = text.split(target)
for frag in range(len(frag_list)-1):
    before = frag_list[frag  ].split()[-1]   # Last  word of left  fragment
    after  = frag_list[frag+1].split()[0 ]   # First word of right fragment
    # Do what you need to with the two words.

这有帮助吗?

这给出了
类型错误:“内置函数”或“方法”对象不可下标
他在
拆分后缺少括号
索引o/p是空字符串。请您的问题清楚地说明要求和预期输出。已修复。对不起