簡體   English   中英

如何從代碼配置 nltk 數據目錄?

[英]How to config nltk data directory from code?

如何從代碼配置 nltk 數據目錄?

只需更改nltk.data.path項目,這是一個簡單的列表。

從代碼, 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.data.path.append('/libs/nltk_data/')

nltk.data.path.append('your/path/to/nltk_data')沒有將nltk.data.path.append('your/path/to/nltk_data')到每個腳本中,而是接受 NLTK_DATA 環境變量。 代碼鏈接

使用文本編輯器(例如nanovimgedit )打開~/.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添加到myapp_uwsgi.ini

env = NLTK_DATA=/home/myuser/nltk_data/

這將設置環境變量NLTK_DATA ,如NLTK_DATA所建議的。
進行此更改后,您可能需要重新啟動 uwsgi 進程。

另一個解決方案是搶先一步。

嘗試導入 nltk nltk.download()

當彈出窗口詢問您是否要下載語料庫時,您可以在那里指定要將其下載到哪個目錄。

使用上面 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")

異常消失了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM