【发布时间】:2012-08-19 22:20:48
【问题描述】:
假设我有以下段落:
"This is the first sentence. This is the second sentence? This is the third
sentence!"
我需要创建一个函数,它只返回给定字符数下的句子数。如果小于一个句子,则返回第一个句子的所有字符。
例如:
>>> reduce_paragraph(100)
"This is the first sentence. This is the second sentence? This is the third
sentence!"
>>> reduce_paragraph(80)
"This is the first sentence. This is the second sentence?"
>>> reduce_paragraph(50)
"This is the first sentence."
>>> reduce_paragraph(5)
"This "
我从这样的事情开始,但我似乎无法弄清楚如何完成它:
endsentence = ".?!"
sentences = itertools.groupby(text, lambda x: any(x.endswith(punct) for punct in endsentence))
for number,(truth, sentence) in enumerate(sentences):
if truth:
first_sentence = previous+''.join(sentence).replace('\n',' ')
previous = ''.join(sentence)
【问题讨论】:
-
“你好,史密斯先生。”应该怎么办?
Mr.后面的点应该解释为句末吗?为什么不使用可以将文本解析成句子的现有库,而不是使用自己的库? -
@MarkByers,如果人们仍然意识到 Mr. 是一个缩写,我会在天堂,但不幸的是,我认为它不再那么常见了。
-
如果有现有的库,我很乐意使用它。
-
您应该查看nltk.org 以获得更好的分句方式
-
@David542:你接受了
ntlk.tokenize对previous question 的回答:对你没有用吗?
标签: python