【问题标题】:Extract a Sentence Containing a Word Using Python... As well as the sentences around it?使用 Python 提取包含单词的句子......以及它周围的句子?
【发布时间】:2014-07-11 00:41:53
【问题描述】:

在提取包含单词的特定句子(如 extract a sentence using pythonPython extract sentence containing word)时,有很多问题,我有足够的 NLTK 和 SciPy 初学者经验,能够自己做到这一点.

但是,我在尝试提取包含一个单词的句子时遇到了困难……以及目标句子之前和之后的句子。

例如:

“前几天我正在上学路上下雨了。我伸手去拿我的雨伞,但我意识到我把它忘在家里了。我该怎么办?我立刻跑到最近的树上。但是然后我意识到我不能一直尝试一棵没有叶子的树。”

在本例中,目标词是“可以”。如果我想提取目标句子(我能做什么?)以及前后句子(我伸手去拿我的雨伞,但我意识到我把它忘在家里了。 我立即跑向最近的树。),什么是好的方法?

假设我将每个段落分割成自己的文本...

for paragraph in document:
    do something

...有没有合适的方法来解决这个问题?我有大约 10,000 个段落,目标词周围有不同数量的句子(出现在每个段落中)。

【问题讨论】:

  • 您是否将每个段落中的句子提取到一个列表中(每个句子一个列表项)?
  • 您需要找到目标词在段落中的每一个次出现,还是只找到第一次出现?

标签: python regex nlp nltk text-segmentation


【解决方案1】:

这样的事情呢?

import nltk.data
tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')
for paragraph in document:
    paragraph_sentence_list = tokenizer.tokenize(paragraph)
    for line in xrange(0,len(paragraph_sentence_list)):
        if 'could' in paragraph_sentence_list[line]:

            print(paragraph_sentence_list[line])

            try:
                print(paragraph_sentence_list[line-1])
            except IndexError as e:
                print('Edge of paragraph. Beginning.')
                pass

            try:
                print(paragraph_sentence_list[line+1])
            except IndexError as e:
                print('Edge of paragraph. End.')
                pass

这样做是将段落分成句子列表。

对句子的迭代测试“可能”是否在句子中。如果是,则打印上一个索引 [line-1]、当前索引 [line] 和下一个索引 [line+1]

【讨论】:

  • 也许在上一行/下一行打印语句周围加上try:/except: IndexError 来处理边缘情况?
  • 使用 NLTK 拆分器比 split('. ') 更好吗?
  • @user1993 它有一些额外的助手nltk.org/_modules/nltk/tokenize/…,但除此之外基本相同。
【解决方案2】:

利用sent_tokenize从原始语料库中提取句子,然后word_tokenize对句子进行标记,然后提取带有“可以”的句子:

>>> from nltk.corpus import brown
>>> from nltk import sent_tokenize, word_tokenize
>>> corpus = " ".join(brown.words())
>>> [i for i in sent_tokenize(corpus) if u"could" in word_tokenize(i)]

获取前后句子:

>>> sentences = sent_tokenize(corpus)
>>> [" ".join([sentences[i-1], j, sentences[i+1]]) for i,j in enumerate(sentences) if u"could" in word_tokenize(j)]

【讨论】:

  • 如何使用 NLTK 拆分器比 split('. ') 更好?
  • len(sent_tokenize('Dr. Ken works at the the hospital')) == 1
  • len('Dr. Ken works at the the hospital'.split('. ')) == 2
  • 谢谢!那么 NLTK 是否更好,因为它在通过大型数据库后提取了很多 更多 仔细的规则/条件?这些规则是硬编码的还是学习的?
猜你喜欢
  • 2013-04-08
  • 1970-01-01
  • 1970-01-01
  • 2013-09-02
  • 1970-01-01
  • 2021-01-22
  • 1970-01-01
相关资源
最近更新 更多