执行句子拆分

许多 NLP 过程需要将大量文本分割成句子。 这似乎是一个简单的任务,但对于计算机来说可能会出现问题。 简单的句子拆分器可以仅查找句点 (.),或使用其他算法,例如预测分类器。 我们将研究 NLTK 的两种句子分割方法。

如何做

我们将使用 07/sentence1.txt 文件中存储的句子。 它具有以下内容,取自 StackOverflow 上的随机职位列表:

我们正在寻找在 ASP.NET、C#、SQL Server 和 AngularJS 方面具有丰富经验的开发人员。 我们是一个快节奏、高度迭代的团队,必须随着工厂的发展而快速适应。 我们需要能够轻松解决新问题、创新解决方案并每天与公司各个方面进行互动的人才。 有创造力、积极主动、能够承担责任并支持您创建的应用程序。 帮助我们更快地发射火箭!

句子拆分的第一个示例位于 07/01_sentence_splitting1.py 文件中。 这使用了 NLTK 中内置的句子分割器,它使用内部边界检测算法:

  1. 首先我们从 NLTK 导入句子分词器:

    from nltk.tokenize import sent_tokenize
    python
  2. 然后加载文件:

    with open('sentence1.txt', 'r') as myfile:
        data=myfile.read().replace('\n', '')
    python
  3. 然后使用 sent_tokenize 对句子进行分割,并报告句子:

    sentences = sent_tokenize(data)
    for s in sentences:
        print(s)
    python

    这会产生以下输出:

    We are seeking developers with demonstrable experience in: ASP.NET, C#, SQL
    Server, and AngularJS.
    We are a fast-paced, highly iterative team that has to adapt quickly as our
    factory grows.
    We need people who are comfortable tackling new problems, innovating
    solutions, and interacting with every facet of the company on a daily
    basis.
    Creative, motivated, able to take responsibility and support the
    applications you create.
    Help us get rockets out the door faster!
    bash
  4. 如果您想创建自己的分词器并自行训练,那么您可以使用 PunktSentenceTokenizer 类。 sent_tokenize 其实是这个类的派生类,默认实现了英文的句子分割。 但您可以选择 17 种不同的语言模型:

    Michaels-iMac-2:~ michaelheydt$ ls ~/nltk_data/tokenizers/punkt
    PY3 finnish.pickle portuguese.pickle
    README french.pickle slovene.pickle
    czech.pickle german.pickle spanish.pickle
    danish.pickle greek.pickle swedish.pickle
    dutch.pickle italian.pickle turkish.pickle
    english.pickle norwegian.pickle
    estonian.pickle polish.pickle
    bash
  5. 您可以通过语言参数选择所需的语言。 例如,以下内容将根据使用德语进行拆分:

    sentences = sent_tokenize(data, language="german")
    python

还有更多

要了解有关该算法的更多信息,您可以阅读以下网站上的源文件:http:// citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.85.5017rep=rep1type=pdf。