用Python中的字典来处理索引统计的方法

作者:xrzs 时间:2022-05-28 19:43:45 

最近折腾索引引擎以及数据统计方面的工作比较多, 与 Python 字典频繁打交道, 至此整理一份此方面 API 的用法与坑法备案.

    索引引擎的基本工作原理便是倒排索引, 即将一个文档所包含的文字反过来映射至文档; 这方面算法并没有太多花样可言, 为了增加效率, 索引数据尽可往内存里面搬, 此法可效王献之习书法之势, 只要把十八台机器内存全部塞满, 那么基本也就功成名就了. 而基本思路举个简单例子, 现在有以下文档 (分词已经完成) 以及其包含的关键词


 doc_a: [word_w, word_x, word_y]
 doc_b: [word_x, word_z]
 doc_c: [word_y]

将其变换为


 word_w -> [doc_a]
 word_x -> [doc_a, doc_b]
 word_y -> [doc_a, doc_c]
 word_z -> [doc_b]

    写成 Python 代码, 便是
 


doc_a = {'id': 'a', 'words': ['word_w', 'word_x', 'word_y']}
doc_b = {'id': 'b', 'words': ['word_x', 'word_z']}
doc_c = {'id': 'c', 'words': ['word_y']}

docs = [doc_a, doc_b, doc_c]
indices = dict()

for doc in docs:
 for word in doc['words']:
   if word not in indices:
     indices[word] = []
   indices[word].append(doc['id'])

print indices

    不过这里有个小技巧, 就是对于判断当前词是否已经在索引字典里的分支
 


if word not in indices:
 indices[word] = []

可以被  dict  的  setdefault(key, default=None)  接口替换. 此接口的作用是, 如果  key  在字典里, 那么好说, 拿出对应的值来; 否则, 新建此  key , 且设置默认对应值为  default . 但从设计上来说, 我不明白为何  default  有个默认值  None , 看起来并无多大意义, 如果确要使用此接口, 大体都会自带默认值吧, 如下
 


for doc in docs:
 for word in doc['words']:
   indices. setdefault(word, []) .append(doc['id'])

    这样就省掉分支了, 代码看起来少很多.
    不过在某些情况下,  setdefault  用起来并不顺手: 当  default  值构造很复杂时, 或产生  default  值有副作用时, 以及一个之后会说到的情况; 前两种情况一言以蔽之, 就是  setdefault  不适用于  default  需要惰性求值的场景. 换言之, 为了兼顾这种需求,  setdefault  可能会设计成
 


def setdefault(self, key, default_factory):
 if key not in self:
   self[key] = default_factory()
 return self[key]

倘若真如此, 那么上面的代码应改成
 


for doc in docs:
 for word in doc['words']:
   indices.setdefault(word, list ).append(doc['id'])

不过实际上有其它替代方案, 这个最后会提到.

    如果说上面只是一个能预见但实际上可能根本不会遇到的 API 缺陷, 那么下面这个就略打脸了.
    考虑现在要进行词频统计, 即一个词在文章中出现了多少次, 如果直接拿  dict  来写, 大致是
 


def word_count(words):
 count = dict()
 for word in words:
   count.setdefault(word, 0) += 1
 return count

print word_count(['hiiragi', 'kagami', 'hiiragi', 'tukasa', 'yosimizu', 'kagami'])

    当你兴致勃勃地跑起上面代码时, 代码会以迅雷不及掩脸之势把异常甩到你鼻尖上 --- 因为出现在  +=  操作符左边的  count.setdefault(word, 0)  在 Python 中不是一个左值. 怎样, 现在开始念叨 C艹 类型体系的好了吧.

    因为 Python 把默认的字面常量  {}  等价于  dict()  就认为  dict  是银弹的思想是要不得的; Python 里面各种数据结构不少, 解决统计问题, 理想的方案是  collections.defaultdict  这个类. 下面的代码想必看一眼就明白
 


from collections import defaultdict

doc_a = {'id': 'a', 'words': ['word_w', 'word_x', 'word_y']}
doc_b = {'id': 'b', 'words': ['word_x', 'word_z']}
doc_c = {'id': 'c', 'words': ['word_y']}

docs = [doc_a, doc_b, doc_c]
indices = defaultdict(list)

for doc in docs:
 for word in doc['words']:
   indices[word].append(doc['id'])

print indices

def word_count(words):
 count = defaultdict(int)
 for word in words:
   count[word] += 1
 return count

print word_count(['hiiragi', 'kagami', 'hiiragi', 'tukasa', 'yosimizu', 'kagami'])

    完满解决了之前遇到的那些破事.

    此外  collections  里还有个  Counter , 可以粗略认为它是  defaultdict(int)  的扩展.

标签:Python
0
投稿

猜你喜欢

  • 很快大多数网民将放弃IE浏览器

    2009-02-04 16:43:00
  • 微信小程序日期选择器实例代码

    2023-08-19 00:22:57
  • javascript用回车键实现Tab键功能

    2009-07-05 18:40:00
  • ASP幻灯片

    2009-09-04 18:05:00
  • Python 文件读写操作实例详解

    2023-08-04 10:41:53
  • PHP设计模式中的命令模式

    2023-05-27 21:13:43
  • PHP中round()函数对浮点数进行四舍五入的方法

    2023-11-23 21:35:24
  • python开发之IDEL(Python GUI)的使用方法图文详解

    2023-09-15 23:22:42
  • instanceof 内部机制探析

    2009-09-25 13:09:00
  • php基于websocket搭建简易聊天室实践

    2023-11-17 12:45:42
  • Oracle数据安全面面观

    2010-07-27 13:27:00
  • 利用Python的Django框架中的ORM建立查询API

    2023-11-15 10:06:03
  • Dreamweaver行为体验

    2007-02-03 11:39:00
  • python实现转盘效果 python实现轮盘抽奖游戏

    2023-03-06 00:00:57
  • PHP 字符串 小常识

    2023-11-20 22:08:32
  • base href 使用方法详解

    2008-05-18 13:27:00
  • js插入flash可防止虚线框激活

    2009-03-13 13:31:00
  • asp如何制作一个股票滚屏显示面板?

    2010-07-07 12:27:00
  • jQuery使用手册--核心篇(Core)

    2007-11-22 22:05:00
  • MySQL时间字段究竟使用INT还是DateTime

    2010-03-09 14:46:00
  • asp之家 网络编程 m.aspxhome.com