Skip to main content
 首页 » 编程设计

python之使用 python 进行文本搜索

2025年05月04日8虾米姐

我正在从事一个文本搜索项目,并使用文本 blob 从文本中搜索句子。 TextBlob 有效地提取所有带有关键字的句子。但是,为了进行有效的研究,我还想在我无法理解的之前和之后抽出一句话。

下面是我使用的代码:

def extraxt_sents(Text,word): 
    search_words = set(word.split(',')) 
        sents = ''.join([s.lower() for s in Text]) 
        blob = TextBlob(sents) 
    matches = [str(s) for s in blob.sentences if search_words & set(s.words)] 
    print search_words 
    print(matches) 

请您参考如下方法:

如果你想得到匹配前后的行,你可以创建一个循环并记住上一行,或者使用slices。 ,例如 blob.sentences 列表中的 [from:to]。

最好的方法可能是使用 enumerate bool 函数。

match_region = [map(str, blob.sentences[i-1:i+2])     # from prev to after next 
                for i, s in enumerate(blob.sentences) # i is index, e is element 
                if search_words & set(s.words)]       # same as your condition 

此处,blob.sentences[i-1:i+2] 将提取从索引 i-1(含)到索引 i 的子列表+2(独占),map 将此列表中的元素转换为字符串。

注意:实际上,您可能希望将 i-1 替换为 max(0, i-1);否则 i-1 可能是 -1 并且 Python 会将其解释为最后一个元素,从而产生一个空切片。另一方面,如果 i+2 大于列表的长度,这将不是问题。