【问题标题】:Splitting Paragraphs in Python using Regular Expression containing abbreaviations使用包含缩写的正则表达式在 Python 中拆分段落
【发布时间】:2011-08-10 20:16:13
【问题描述】:

尝试在包含 3 个字符串和缩写的段落上使用此功能。

#!/usr/bin/env python
# -*- coding: UTF-8 -*-

def splitParagraphIntoSentences(paragraph):
    ''' break a paragraph into sentences
        and return a list '''
    import re
    # to split by multile characters

    #   regular expressions are easiest (and fastest)
    sentenceEnders = re.compile('[.!?][\s]{1,2}[A-Z]')
    sentenceList = sentenceEnders.split(paragraph)
    return sentenceList

if __name__ == '__main__':
    p = "While other species (e.g. horse mango, M. foetida) are also grown ,Mangifera indica – the common mango or Indian mango – is the only mango tree. Commonly cultivated in many tropical and subtropical regions, and its fruit is distributed essentially worldwide.In several cultures, its fruit and leaves are ritually used as floral decorations at weddings, public celebrations and religious "

    sentences = splitParagraphIntoSentences(p)
    for s in sentences:
        print s.strip()

下一个开头句的第一个字符被淘汰,

收到的 O/p: 而其他芒果属物种(例如马芒果、M. foetida)也生长在 更本地化的基础,Mangifera indica ΓÇô 普通芒果或印度芒果 ΓÇô 是唯一的芒果树 热带、亚热带多地区普遍栽培,果实多 基本上分布于世界各地。在几种文化中,它的果实和叶子都是 ri 最终用作婚礼、公共庆典和宗教活动的花卉装饰。

因此字符串被拆分为仅2个字符串,并且下一句的第一个字符被消除。还可以看到一些奇怪的字符,我猜python无法转换连字符。

如果我将正则表达式更改为 [.!?][\s]{1,2}

而其他物种(例如 马芒果,M foetida) 也种植,Mangifera indica ΓÇô 普通芒果或印度芒果Γ Çô是唯一的芒果树 热带、亚热带多地区普遍栽培,果实多 基本上分布于世界各地。在几种文化中,它的果实和叶子是 r 通常用作婚礼、公共庆典和宗教场合的花卉装饰 s

因此,即使是缩写也会被拆分。

【问题讨论】:

  • 请仅发布排序、自包含、正确的示例 -> sscce.org
  • 他得到了什么,他想要得到什么,一清二楚。他只是没有正确格式化。
  • 直到你回答我才明白他想要什么。

标签: python regex split


【解决方案1】:

你想要的正则表达式是:

[.!?][\s]{1,2}(?=[A-Z])

你想要一个肯定的前瞻断言,这意味着你想要匹配后面跟着大写字母的模式,但不匹配大写字母

只有第一个匹配的原因是您在第二个句点之后没有空格。

【讨论】:

  • [\s] 是怎么回事?不应该是\s吗?
  • 我没有过多地编辑它。两者是等价的。
  • @agf:非常感谢您的回复。它解决了问题:) 你能告诉我是否有办法解决特殊字符问题。
  • 试试sentenceEnders.split(paragraph, re.UNICODE)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多