【问题标题】:python truncate text around keywordpython截断关键字周围的文本
【发布时间】:2010-11-30 22:43:26
【问题描述】:

我有一个字符串,我想在其中搜索关键字或短语,并只返回关键字或短语之前和之后的部分文本。 Google 完全按照我的意思行事。

这是我从网上抓取的一个字符串:

“这个过滤器像原始的 djancate words Django 过滤器一样截断单词,但不是基于单词的数量,而是基于字符的数量。我在构建一个网站时发现需要这个必须在非常小的文本框上显示标签,并且按单词截断并不总是给我最好的结果(按字符截断......嗯......不是那么优雅)。”

现在假设我想在此搜索短语 building a website,然后输出如下内容:

...建立网站我必须展示的地方...

编辑:我应该更清楚地说明这一点。这必须适用于多个字符串/短语,而不仅仅是这个。

【问题讨论】:

  • 这几乎是一个 kwic(上下文中的关键字)结果
  • 感谢您的任期,我​​知道我没有在寻找正确的东西。

标签: python


【解决方案1】:

基于其他人(尤其是 cababunga 的)的答案,我喜欢一个函数,它最多需要 25 个(或很多)字符,在最后一个单词边界处停止,并提供一个很好的匹配:

import re

def find_with_context(haystack, needle, context_length, escape=True):
    if escape:
        needle = re.escape(needle)
    return re.findall(r'\b(.{,%d})\b(%s)\b(.{,%d})\b' % (context_length, needle, context_length), haystack)

# Returns a list of three-tuples, (context before, match, context after).

用法:

>>> find_with_context(s, 'building a website', 25)
[(' the need for this when ', 'building a website', " where i'd have to show ")]
>>> # Compare this to what it would be without making sure it ends at word boundaries:
... # [('d the need for this when ', 'building a website', " where i'd have to show l")]
...
>>> for match in find_with_context(s, 'building a website', 25):
...     print '<p>...%s<strong>%s</strong>%s...</p>' % match
... 
<p>... the need for this when <strong>building a website</strong> where i'd have to show ...</p>

【讨论】:

  • 我很困惑,上下文长度是多少?你能举个例子吗?
  • @bababa:答案已更新以澄清这一点(并修复了我遇到的停止错误)
  • 这正是我想要的。我不太熟悉正则表达式。有没有办法让 context_length 在空格处截断,以免单词被切成两半?
  • @bababa:这正是我正在做的 - 比较使用示例的第二行(我的)和第四行(没有单词边界查找)。请注意,在当前状态下,我的每端可能有也可能没有空格;开头的那些可以在正则表达式中去掉,但我想不出最后的方法(由于贪婪的工作方式从左到右)。 str.strip() 是处理它的最简单方法 - 或者只是添加一个空格,它在 HTML 中无关紧要。
【解决方案2】:

使用获取所需短语索引的方法,然后在该索引之前和之后将字符串分割为 N 个字符。您可以通过在每一侧查找距该索引最接近 N 个字符的空格来获得幻想,这样您就可以得到整个单词。

用 Python 字符串函数找到您需要的确切函数:

http://docs.python.org/py3k/library/strings.html

【讨论】:

    【解决方案3】:
    >>> re.search(r'((?:\S+\s+){,5}\bbuilding a website\b(?:\s+\S+){,5})', s).groups()
    ("the need for this when building a website where i'd have to show",)
    

    【讨论】:

      【解决方案4】:

      可能是这样的:

      import re
      mo = re.search(r"(.{25})\bbuilding a website\b(.{25})", text)
      if mo:
          print mo.group(1), "<b>building a website</b>", mo.group(2)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-07-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-17
        • 1970-01-01
        • 1970-01-01
        • 2020-04-26
        相关资源
        最近更新 更多