python加载自定义词典实例

yipeiwu_com6年前Python基础

如下所示:

#加载词典
def load_dict_from_file(filepath):
  _dict = {}
  try:
    with io.open(filepath, 'r',encoding='utf-8') as dict_file:
      for line in dict_file:
        (key, value) = line.strip().split(' ') #将原本用空格分开的键和值用冒号分开来,存放在字典中
        _dict[key] = value
  except IOError as ioerr:
    print("文件 %s 不存在" % (filepath))
  return _dict
#加载停用词词典
def stopwordslist(filepath):
  stopwords = {}
  fstop = io.open(filepath, 'r',encoding='utf-8')
  for line in fstop:
    stopwords[line.strip()]=line.strip()
  fstop.close()
  return stopwords

以上这篇python加载自定义词典实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

《Python之禅》中对于Python编程过程中的一些建议

《Python之禅》中对于Python编程过程中的一些建议

围绕一门语言,学习它的文化精髓,能让你成为一名更优秀的程序员。如果你还没读过Python之禅(Zen of Python) ,那么打开Python的命令提示符输入import this,...

python datetime中strptime用法详解

python 中datetime中strptime用法,具体代码如下所示: import datetime day20 = datetime.datetime.strptime('2...

Python pymongo模块常用操作分析

Python pymongo模块常用操作分析

本文实例讲述了Python pymongo模块常用操作。分享给大家供大家参考,具体如下: 环境:pymongo3.0.3,python3 以下是我整理的一些关于pymongo的操作,网上...

在Python中过滤Windows文件名中的非法字符方法

网上有三种写法: 第一种(所有非法字符都不转义): def setFileTitle(self,title): fileName = re.sub('[\/:*&#...

python3解析库pyquery的深入讲解

前言 pyquery是一个类似jquery的python库,它实现能够在xml文档中进行jQuery查询,pyquery使用lxml解析器进行快速在xml和html文档上操作,它提供了和...