NLP劃分句子的正則改進(tokenize)方法

1 引言

在自然語言處理NLP中,我們需要把一個段落劃分為單句。英語中單句的劃分是以句號"."為界的,也就是說,只要遇到"."就開始斷句。但如果句子中包含有Mr., Ph.D., Jr. 這樣的單詞時, 句子就不應該在此斷開。幸運的是,nltk的tokenize已經考慮了這些特殊詞匯。例如這樣一個段落:mytext ="Mr. Johnson Jr. got his Ph.D. in U.S.A but he worked for ABCD Associatess Ltd. in Canada. He had wide reaserch interests in geotechnical engineering, e.g. slope stability, underground excavation, machine foundation, earthquake engineering, etc. " .  

from nltk import tokenizemytext = tokenize.sent_tokenize(mytext)

不過,tokenize把這個段落劃分成了三個句子,它未能正確處理"e.g."后的斷句問題. 

(1) Mr. Johnson Jr. got his Ph.D. in U.S.A but he worked for ABCD Associatess Ltd. in Canada.

(2) He had wide reaserch interests in geotechnical engineering, e.g.

(3) slope stability, underground excavation, machine foundation, earthquake engineering, etc. 

這個筆記使用正則表達式改進了tokenize,同時也部分解決了在劃分參考文獻時遇到的問題。

NLP劃分句子的正則改進(tokenize)方法的圖1


2 e.g.問題

這個改進相對簡單,我們使用正式表達式加一個判斷語句,這樣就不會在e.g.時出現斷句,于是正確地劃分了句子,如下所示:

if "e.g." in text: text = text.replace("e.g.","e<prd>g<prd>")

(1) Mr. Johnson Jr. got his Ph.D. in U.S.A but he worked for ABCD Associatess Ltd. in Canada.

(2) He had wide reaserch interests in geotechnical engineering, e.g. slope stability, underground excavation, machine foundation, earthquake engineering, etc.


3 參考文獻問題

參考文獻的句子劃分比較麻煩。最常見的一種格式是作者年份后面加"." ,例如下面的參考文獻格式,使用tokenize會從(2007)后面的"." 把句子斷開,顯然這不是我們想要的結果。

Karami, A., S. Greer and R. Beddoes (2007). Numerical Assessment of Step-Path Failure of Northwest Wall of A154 Pit, Diavik Diamond Mines. 

(1) Karami, A., S. Greer and R. Beddoes (2007).

(2) Numerical Assessment of Step-Path Failure of Northwest Wall of A154 Pit, Diavik Diamond Mines.

目前沒有想到更簡潔的方法,只能使用下面的代碼單個進行硬處理,解決了這個問題。不過,有些文獻在Beddoes后面也加上了".", 遇到這種情況就沒辦法了,不得不在Beddoes后面斷開。遇到這種情況,在整理文獻的過程中,可以手工把"."去掉。

if "0)." in text: text = text.replace("0).","0)<prd>")if "1)." in text: text = text.replace("1).","1)<prd>")if "2)." in text: text = text.replace("2).","2)<prd>")if "3)." in text: text = text.replace("3).","3)<prd>")if "4)." in text: text = text.replace("4).","4)<prd>")if "5)." in text: text = text.replace("5).","5)<prd>")if "6)." in text: text = text.replace("6).","6)<prd>")if "7)." in text: text = text.replace("7).","7)<prd>")if "8)." in text: text = text.replace("8).","8)<prd>")if "9)." in text: text = text.replace("9).","9)<prd>")

由于參考文獻的書寫格式沒有統一格式,特別是遇到雜志名稱的縮寫,例如:

"Cook, N. G. W., 1965. "The Failure of Rock." Int. J. Rock Mech. Min. Sci. 2:", 對于這樣的縮寫,只能通過單獨的正則表達式來處理:

prefixes = "(Mr|St|Mrs|Ms|Dr|Int|Proc|Vol|al|Min|Mech|1|2|3|4|5|6|7|8|9)[.]"

處理后劃分成如下兩個句子:

(1) Cook, N. G. W., 1965. "The Failure of Rock".

(2) Int. J. Rock Mech. Min. Sci.

4 結束語

通過引入正則表達式改進了目前句子劃分存在的兩個問題:一個是在句中e.g.后的斷句,另一個是在參考文獻中的年代,例如 (2021). 后的斷句,極大地改善了劃分句子的質量。不過,就像上面最后一個例句顯示的那樣,還沒有找到一種方法把題目名稱與雜志名稱鏈接起來。 


登錄后免費查看全文
立即登錄
App下載
技術鄰APP
工程師必備
  • 項目客服
  • 培訓客服
  • 平臺客服

TOP