在linux环境下,没有root权限的情况下,有时会碰到如下问题:

Building prefix dict from the default dictionary ...
Loading model from cache /tmp/jieba.cache
Dumping model to file cache /tmp/jieba.cache
Dump cache file failed.
Traceback (most recent call last):
File "/home/work/anaconda3/envs/py27/lib/python2.7/site-packages/jieba/__init__.py", line , in initialize
_replace_file(fpath, cache_file)
OSError: [Errno ] Operation not permitted

这是因为jieba默认情况下在/tmp下存储缓存文件,然而不是root用户,权限不够。解决办法是修改默认缓存文件的目录,把缓存文件放在用户的目录下面。 jieba文档提到了tmp_dir和cache_file可以改,所以我们查看了下源码

/home/work/anaconda3/envs/py27/lib/python2.7/site-packages/jieba/__init__.py,文件52行-66行如下:
class Tokenizer(object):

    def __init__(self, dictionary=DEFAULT_DICT):
self.lock = threading.RLock()
if dictionary == DEFAULT_DICT:
self.dictionary = dictionary
else:
self.dictionary = _get_abs_path(dictionary)
self.FREQ = {}
self.total =
self.user_word_tag_tab = {}
self.initialized = False
self.tmp_dir = None
# self.tmp_dir = '/'
self.cache_file = None

修改源码,在64行self.tmp_dir中可以设置自定义缓存路径。

另外一种方式是在代码中修改,以下是jieba单例模式demo

 class Singleton(object):
"""
Jieba Utils Class
"""
_instance = None def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
return cls._instance class JiebaUtil(Singleton):
"""
jiebautil 工具包
"""
_jieba_instance = None def get_instance(self):
"""
get the global jieba instance
"""
if self._jieba_instance:
return self._jieba_instance
print 'initialize...'
obj = jieba.Tokenizer()
obj.tmp_dir = dirpath
obj.load_userdict(user_dict_path)
obj.initialize()
self._jieba_instance = obj
return obj if __name__ == '__main__': one = JiebaUtil()
two = JiebaUtil() print one == two tkn = one.get_instance()
tkn2 = one.get_instance()
print tkn == tkn2 print id(one), id(two) print id(tkn), id(tkn2)

在27行中可以设置自定义的他们tmp_dir缓存路径。

参考:

http://funhacks.net/2017/01/17/singleton/

https://blog.csdn.net/sijiaqi11/article/details/78601258

最新文章

  1. C语言栈调用机制初探
  2. 用(*.frm *.MYD *.MYI)文件恢复MySql数据库
  3. POJ C++程序设计 编程题#2 编程作业—多态与虚函数
  4. MySQL之Join
  5. 4.VS2010C++建立DLL工程
  6. JQuery焦点Table
  7. Postman newman
  8. 关于oracle动态视图v$datafile和v$datafile_header(转)
  9. 关于ECSHOP模板架设的服务器php版本过高报错的解决方法(二)
  10. 从网络通信角度谈web性能优化
  11. C# Redis实战(六)
  12. 针对于Python的OpenCV环境搭建
  13. Zsh安装及常用操作
  14. HDU4278
  15. Java并发编程快速学习
  16. localhost/get/user.json localhost/get/user.xml
  17. Win10 Ubuntu 双系统 卸载 Ubuntu
  18. OpenCL 存储器次序的验证
  19. MySql社区版和企业版的区别
  20. /.nav-tabs :是普通标签页 .nav-pills:胶囊式标签页 action ;默认的激活项,给<li>加默认显示的是哪个标签页内容 .nav是标签页的一个基类,给ul加 .nav-stacked: 垂直排列BootStrap

热门文章

  1. 使用Makefile编译Erlang
  2. js 页面向下滚动
  3. PHP curl_multi_info_read函数
  4. legend2---17、legend2里面怎么面向对象
  5. python sum()函数的用法
  6. TIOBE 编程语言排行榜是什么,它是如何计算编程语言排行的?
  7. 微信小程序,获取二维码
  8. 使用Microsoft.Practices.Unity 依赖注入 转载https://www.cnblogs.com/slardar1978/p/4205394.html
  9. 2019ccpc网络赛hdu6703 array(线段树)
  10. ACM 中的对拍程序