jieba分词单例模式及linux权限不够情况下tmp_dir自定义
2024-09-06 05:01:24
在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
最新文章
- C语言栈调用机制初探
- 用(*.frm *.MYD *.MYI)文件恢复MySql数据库
- POJ C++程序设计 编程题#2 编程作业—多态与虚函数
- MySQL之Join
- 4.VS2010C++建立DLL工程
- JQuery焦点Table
- Postman newman
- 关于oracle动态视图v$datafile和v$datafile_header(转)
- 关于ECSHOP模板架设的服务器php版本过高报错的解决方法(二)
- 从网络通信角度谈web性能优化
- C# Redis实战(六)
- 针对于Python的OpenCV环境搭建
- Zsh安装及常用操作
- HDU4278
- Java并发编程快速学习
- localhost/get/user.json localhost/get/user.xml
- Win10 Ubuntu 双系统 卸载 Ubuntu
- OpenCL 存储器次序的验证
- MySql社区版和企业版的区别
- /.nav-tabs :是普通标签页 .nav-pills:胶囊式标签页 action ;默认的激活项,给<;li>;加默认显示的是哪个标签页内容 .nav是标签页的一个基类,给ul加 .nav-stacked: 垂直排列BootStrap
热门文章
- 使用Makefile编译Erlang
- js 页面向下滚动
- PHP curl_multi_info_read函数
- legend2---17、legend2里面怎么面向对象
- python sum()函数的用法
- TIOBE 编程语言排行榜是什么,它是如何计算编程语言排行的?
- 微信小程序,获取二维码
- 使用Microsoft.Practices.Unity 依赖注入 转载https://www.cnblogs.com/slardar1978/p/4205394.html
- 2019ccpc网络赛hdu6703 array(线段树)
- ACM 中的对拍程序