1. 程式人生 > 程式設計 >python載入自定義詞典例項

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,encoding='utf-8')
  for line in fstop:
    stopwords[line.strip()]=line.strip()
  fstop.close()
  return stopwords

以上這篇python載入自定義詞典例項就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。