2010-07-05 121 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