2010-07-05 167 views
23

如何檢測使用NLTK編寫文本的語言?NLTK和語言檢測

我見過的例子使用nltk.detect,但是當我在我的Mac上安裝它時,我找不到這個包。

回答

26

你有沒有遇到下面的代碼片段?

english_vocab = set(w.lower() for w in nltk.corpus.words.words()) 
text_vocab = set(w.lower() for w in text if w.lower().isalpha()) 
unusual = text_vocab.difference(english_vocab) 

http://groups.google.com/group/nltk-users/browse_thread/thread/a5f52af2cbc4cfeb?pli=1&safe=active

或者下面的演示文件?

https://web.archive.org/web/20120202055535/http://code.google.com/p/nltk/source/browse/trunk/nltk_contrib/nltk_contrib/misc/langid.py

+0

PS,它仍然依賴於nltk.detect,雖然。任何關於如何在Mac上安裝的想法? – niklassaers 2010-08-03 09:59:35

+0

我不相信detect是nltk的本地模塊。 下面是代碼:http://docs.huihoo.com/nltk/0.9.5/api/nltk.detect-pysrc.html 你可以下載它並把它放到你的python庫中,它可能在: /Library/Python/2.x/site-packages/nltk ... – 2010-08-03 13:53:12

+0

檢查出來.. http://blog.alejandronolla.com/2013/05/15/detecting-text-language-with-python -and-nltk/ – 2016-04-08 05:46:04

18

這個圖書館不是來自NLTK,但肯定有幫助。

$ sudo的PIP安裝langdetect

支持Python版本2.6,2.7,3.x的

>>> from langdetect import detect 

>>> detect("War doesn't show who's right, just who's left.") 
'en' 
>>> detect("Ein, zwei, drei, vier") 
'de' 

https://pypi.python.org/pypi/langdetect?

P.S .:不要指望這總是正確的工作:

>>> detect("today is a good day") 
'so' 
>>> detect("today is a good day.") 
'so' 
>>> detect("la vita e bella!") 
'it' 
>>> detect("khoobi? khoshi?") 
'so' 
>>> detect("wow") 
'pl' 
>>> detect("what a day") 
'en' 
>>> detect("yay!") 
'so' 
+1

謝謝你指出它並不總是有效。 '檢測(「你讓它回家!」)'給我「fr」。我想知道是否有更好的。 – 2017-10-14 03:43:51

+1

下面是另一個有趣的觀察:它似乎沒有給每個相同的答案。 >>> >>> detect_langs(「你好,我是christiane amanpour。」) [it:0.8571401485770536,en:0.14285811674731527] >>> detect_langs(「你好,我是christiane amanpour。」) [it:0.8571403121803622, fr:0.14285888197332486] >>> detect_langs(「你好,我是christiane amanpour。」) [it:0.999995562246093]' – 2017-10-14 04:03:25