【问题标题】:How do I split a string into sentences whilst including the punctuation marks?如何在包含标点符号的同时将字符串拆分为句子?
【发布时间】:2019-03-29 11:12:40
【问题描述】:

我希望拆分句子包含标点符号(例如:?、!、.),如果句子末尾有双引号,我也想包含它。

我使用 python3 中的 re.split() 函数将我的字符串拆分为句子。但遗憾的是,生成的字符串不包含标点符号,也不包含双引号(如果句尾出现双引号)。

这是我当前代码的样子:

x = 'This is an example sentence. I want to include punctuation! What is wrong with my code? It makes me want to yell, "PLEASE HELP ME!"'
sentence = re.split('[\.\?\!]\s*', x)

我得到的输出是:

['This is an example sentence', 'I want to include punctuation', 'What is wrong with my code', 'It makes me want to yell, "PLEASE HELP ME', '"']

【问题讨论】:

    标签: regex python-3.x string punctuation sentence


    【解决方案1】:

    尝试向后拆分:

    sentences = re.split('(?<=[\.\?\!])\s*', x)
    print(sentences)
    
    ['This is an example sentence.', 'I want to include punctuation!',
     'What is wrong with my code?', 'It makes me want to yell, "PLEASE HELP ME!"']
    

    当我们看到紧跟在我们身后的标点符号时,这个正则表达式技巧通过拆分来起作用。在这种情况下,我们还会匹配并使用我们前面的任何空格,然后再继续输入字符串。

    这是我处理双引号问题的平庸尝试:

    x = 'This is an example sentence. I want to include punctuation! "What is wrong with my code?"  It makes me want to yell, "PLEASE HELP ME!"'
    sentences = re.split('((?<=[.?!]")|((?<=[.?!])(?!")))\s*', x)
    print filter(None, sentences)
    
    ['This is an example sentence.', 'I want to include punctuation!',
     '"What is wrong with my code?"', 'It makes me want to yell, "PLEASE HELP ME!"']
    

    请注意,它甚至可以正确拆分以双引号结尾的句子。

    【讨论】:

    • 对不起,我在“re”前面有一个括号,所以你的代码中也有它。请编辑它。至于结果,除了字符串末尾的双引号外,一切正常。你跑你的了吗?它对你有用吗?对我来说,引号在结果列表中显示为单独的元素。
    • @investigate311 I didn't have that problem。我们可以调整我的答案来处理双引号。
    • 更新的双引号版本对我有用!我用循环清理了 None 和空字符串。
    猜你喜欢
    • 2012-01-22
    • 2017-01-12
    • 2010-12-25
    • 1970-01-01
    • 1970-01-01
    • 2013-04-14
    • 1970-01-01
    • 2014-08-23
    • 1970-01-01
    相关资源
    最近更新 更多