【问题标题】:Text search using python使用python进行文本搜索
【发布时间】:2014-07-21 12:59:26
【问题描述】:

我正在从事一个文本搜索项目,并使用文本 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)

【问题讨论】:

  • 您的代码中是否存在一些缩进错误?
  • 我建议,看看'nltk'
  • @cengizkrbck TextBlob 似乎比 nltk 工作得更好。我一个,一个不知道前后一个句子。
  • 尝试使用索引:[map(str, blob.sentences[i-1:i+2]) for i, s in enumerate(blob.sentences) if search_words & set(s.words)]
  • @tobias_k 非常感谢 Tobias :)

标签: python textblob


【解决方案1】:

如果你想得到比赛前后的台词,你可以创建一个循环并记住上一句,或者使用slices,比如[from:to]列表中的[from:to]

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

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 大于列表的长度,则不会有问题。

【讨论】:

    猜你喜欢
    • 2014-11-19
    • 1970-01-01
    • 1970-01-01
    • 2016-08-04
    • 2013-04-06
    • 1970-01-01
    • 1970-01-01
    • 2018-09-05
    • 1970-01-01
    相关资源
    最近更新 更多