我必須切斷一個unicode字符串,它實際上是一個文章(包含句子)我想在python中的第X個句子後剪掉這篇文章字符串。Python在第X個句子後切斷了一個字符串
句子結尾的一個很好的指示是它以句號(「。」)結尾,單詞以大寫字母開頭。如
myarticle == "Hi, this is my first sentence. And this is my second. Yet this is my third."
這怎麼能實現?
感謝
我必須切斷一個unicode字符串,它實際上是一個文章(包含句子)我想在python中的第X個句子後剪掉這篇文章字符串。Python在第X個句子後切斷了一個字符串
句子結尾的一個很好的指示是它以句號(「。」)結尾,單詞以大寫字母開頭。如
myarticle == "Hi, this is my first sentence. And this is my second. Yet this is my third."
這怎麼能實現?
感謝
考慮下載Natural Language Toolkit(NLTK
)。然後,您可以創建不會像「美國」這樣的句子中斷的句子。或者無法分割以「?!」結尾的句子。
>>> import nltk
>>> paragraph = u"Hi, this is my first sentence. And this is my second. Yet this is my third."
>>> sentences = nltk.sent_tokenize(paragraph)
[u"Hi, this is my first sentence.", u"And this is my second.", u"Yet this is my third."]
您的代碼變得更具可讀性。要訪問第二句,請使用您習慣的符號。 「」
>>> sentences[1]
u"And this is my second."
試試這個:
'.'.join(re.split('\.(?=\s*[A-Z])', myarticle)[:2]) + '.'
它削減你的字符串中的第二句之後([2])。
但是還是有一些問題(一如果你處理自然語言):最值得注意的是它只會識別以'A-Z'開頭的句子。這可能適用於英語,但不適用於其他語言。
如果有可能比通常的其它標點符號,你應該試試這個:
re.split('\W(?=[A-Z])',ss)
這將返回語句列表。當然,它沒有正確對待保羅提到的案件。
這不適用於像「WWF打破這種情況」。 – EOL 2010-08-05 08:01:37
這裏是一個更強大的解決方案:
myarticle = """This is a sentence.
And another one.
And a 3rd one."""
N = 3 # 3 sentences
print ''.join(sentence+'.' for sentence in re.split('\.(?=\s*(?:[A-Z]|$))', myarticle, maxsplit=N)[:-1])
該解決方案擁有超過提到的其他一些可能性的一些優勢面前:它的工作原理
即使恰好有N
句子你的文字。其他答案在最後會產生雙重.
。這是通過考慮最後一句沒有大寫字母,而是以文字結尾($
)這一事實來避免的。
即使文本中的句子數少於N
,也可以使用。
分割的數量受maxsplit
參數限制爲re.split()
,這限制了分割的次數,因此非常有效。
希望這有助於!
小心那些談論利文斯頓博士,皮博迪先生,李梅教授或奧利裏夫人的句子。 – PaulMcG 2010-08-05 07:05:14
還要注意以句子結尾的句子嗎?要麼 ! – 2010-08-05 07:47:56
或使用省略號的句子... – Nobody 2010-08-05 08:35:30