【问题标题】:Split a string into its sentences using python使用python将字符串拆分成句子
【发布时间】:2019-04-11 20:21:56
【问题描述】:

我有以下字符串:

string = 'This is one sentence  ${w_{1},..,w_{i}}$. This is another sentence. '

现在,我想把它分成两句话。

但是,当我这样做时:

string.split('.')

我明白了:

['This is one sentence  ${w_{1},',
 '',
 ',w_{i}}$',
 ' This is another sentence',
 ' ']

任何人都知道如何改进它,以免检测到“。”在$ $ 内?

另外,你会怎么做:

string2 = 'This is one sentence  ${w_{1},..,w_{i}}$! This is another sentence. Is this a sentence? Maybe !  '

编辑 1:

期望的输出是:

对于字符串 1:

['This is one sentence  ${w_{1},..,w_{i}}$','This is another sentence']

对于字符串 2:

['This is one sentence  ${w_{1},..,w_{i}}$','This is another sentence', 'Is this a sentence', 'Maybe !  ']

【问题讨论】:

  • 你想要的输出是什么?
  • 您应该考虑的一件事是,在 LaTeX 中,正确的省略号是 \ldots,而不是 ...
  • 您将. 设置为分隔符,这就是为什么它会在找到的每个. 处拆分您的字符串,而不管字符串中的上下文如何。
  • @ZevChonoles 是的,当然。我会改变的。但是,问题仍然存在,因为我还有其他情况,我不能简单地替换它。

标签: python string


【解决方案1】:

对于更一般的情况,您可以像这样使用re.split

import re

mystr = 'This is one sentence  ${w_{1},..,w_{i}}$. This is another sentence. '

re.split("[.!?]\s{1,}", mystr)
# ['This is one sentence  ${w_{1},..,w_{i}}$', 'This is another sentence', '']

str2 = 'This is one sentence  ${w_{1},..,w_{i}}$! This is another sentence. Is this a sentence? Maybe !  '

re.split("[.!?]\s{1,}", str2)
['This is one sentence  ${w_{1},..,w_{i}}$', 'This is another sentence', 'Is this a sentence', 'Maybe ', '']

括号中的字符是您选择的标点符号,并且您在\s{1,} 末尾添加至少一个空格以忽略其他没有空格的.。这也将处理您的感叹号案例

这是恢复标点符号的(有点老套)方法

punct = re.findall("[.!?]\s{1,}", str2)
['! ', '. ', '? ', '!  ']

sent = [x+y for x,y in zip(re.split("[.!?]\s{1,}", str2), punct)]
sent
['This is one sentence  ${w_{1},..,w_{i}}$! ', 'This is another sentence. ', 'Is this a sentence? ', 'Maybe !  ']

【讨论】:

  • 非常感谢您的回答,尤其是您最后的破解!真的很酷! +1
【解决方案2】:

您可以将re.findall 与交替模式一起使用。为确保句子以非空格开头和结尾,请在开头使用正向lookahead 模式,在结尾使用正向lookbehind 模式:

re.findall(r'((?=[^.!?\s])(?:$.*?\$|[^.!?])*(?<=[^.!?\s]))\s*[.!?]', string)

这会返回,对于第一个字符串:

['This is one sentence  ${w_{1},..,w_{i}}$', 'This is another sentence']

对于第二个字符串:

['This is one sentence  ${w_{1},', ',w_{i}}$', 'This is another sentence', 'Is this a sentence', 'Maybe']

【讨论】:

  • 非常好!非常感谢您的回答!
【解决方案3】:

使用'. ' (在 . 之后有一个空格)因为它只存在于句子结束时,而不是句子中间。

string = 'This is one sentence  ${w_{1},..,w_{i}}$. This is another sentence. '

string.split('. ')

返回:

['这是一个句子 ${w_{1},..,w_{i}}$', '这是另一个句子', '']

【讨论】:

  • 好主意!但是如果句子格式不好怎么办?也许人们可以忽略$ $ 之间的所有内容?
  • 我不确定。您可以确保所有句子都具有正确的格式,以便当一个句子结束时(带有 .),在下一个句子开始之前有一个空格。这样就永远不会出现错误的格式。您的代码可以这样做吗?
猜你喜欢
  • 2022-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-28
  • 2014-04-23
  • 1970-01-01
相关资源
最近更新 更多