【发布时间】:2011-04-01 03:28:25
【问题描述】:
如何从代码中配置 nltk 数据目录?
【问题讨论】:
标签: python path directory nlp nltk
如何从代码中配置 nltk 数据目录?
【问题讨论】:
标签: python path directory nlp nltk
使用上面 fnjn 的建议打印路径:
print(nltk.data.path)
我在windows上看到了这种格式的路径字符串:
C:\\Users\\my_user_name\\AppData\\Roaming\\SPB_Data
所以当我使用 path.append 时,我将路径从 python 类型的正斜杠“/”切换为双反斜杠“\\”:
nltk.data.path.append("C:\\workspace\\my_project\\data\\nltk_books")
异常消失了。
【讨论】:
另一个解决方案是领先一步。
试试 导入 nltk nltk.download()
当弹出窗口询问您是否要下载语料库时,您可以在其中指定要下载到哪个目录。
【讨论】:
NLTK 接受 NLTK_DATA 环境变量,而不是将 nltk.data.path.append('your/path/to/nltk_data') 添加到每个脚本。 (code link)
使用文本编辑器(例如nano、vim、gedit)打开~/.bashrc(或~/.profile),并添加以下行:
export NLTK_DATA="your/path/to/nltk_data"
执行source加载环境变量
source ~/.bashrc
打开python并执行以下几行
import nltk
nltk.data.path
您可以在其中看到您的 nltk 数据路径。
参考:@alvations 的回答 nltk/nltk #1997
【讨论】:
对于那些使用 uwsgi 的人:
我遇到了麻烦,因为我希望 uwsgi 应用程序(以与我不同的用户身份运行)能够访问我之前下载的 nltk 数据。对我有用的是将以下行添加到myapp_uwsgi.ini:
env = NLTK_DATA=/home/myuser/nltk_data/
按照@schemacs 的建议,这将设置环境变量NLTK_DATA。
进行此更改后,您可能需要重新启动 uwsgi 进程。
【讨论】:
来自代码,http://www.nltk.org/_modules/nltk/data.html:
``nltk:path``: Specifies the file stored in the NLTK data package at *path*. NLTK will search for these files in the directories specified by ``nltk.data.path``.
然后在代码内:
######################################################################
# Search Path
######################################################################
path = []
"""A list of directories where the NLTK data package might reside.
These directories will be checked in order when looking for a
resource in the data package. Note that this allows users to
substitute in their own versions of resources, if they have them
(e.g., in their home directory under ~/nltk_data)."""
# User-specified locations:
path += [d for d in os.environ.get('NLTK_DATA', str('')).split(os.pathsep) if d]
if os.path.expanduser('~/') != '~/':
path.append(os.path.expanduser(str('~/nltk_data')))
if sys.platform.startswith('win'):
# Common locations on Windows:
path += [
str(r'C:\nltk_data'), str(r'D:\nltk_data'), str(r'E:\nltk_data'),
os.path.join(sys.prefix, str('nltk_data')),
os.path.join(sys.prefix, str('lib'), str('nltk_data')),
os.path.join(os.environ.get(str('APPDATA'), str('C:\\')), str('nltk_data'))
]
else:
# Common locations on UNIX & OS X:
path += [
str('/usr/share/nltk_data'),
str('/usr/local/share/nltk_data'),
str('/usr/lib/nltk_data'),
str('/usr/local/lib/nltk_data')
]
要修改路径,只需附加到可能的路径列表:
import nltk
nltk.data.path.append("/home/yourusername/whateverpath/")
或者在窗口中:
import nltk
nltk.data.path.append("C:\somewhere\farfar\away\path")
【讨论】:
nltk/nltk/data
magically_find_nltk_data()
我用append,例子
nltk.data.path.append('/libs/nltk_data/')
【讨论】:
只需更改nltk.data.path的项目,这是一个简单的列表。
【讨论】:
'/home/aankney/nltk_data' 作为列表的第一个元素,但我在服务器上并希望 nltk_data 由使用服务器的其他人共享。如何防止 nltk 将其用作下载路径之一?