在 python 中快速/优化 N-gram 实现

2024-03-28

python 中哪种 ngram 实现速度最快?

我试图分析 nltk 与 scott 的 zip (http://locallyoptimal.com/blog/2013/01/20/elegant-n-gram- Generation-in-python/ http://locallyoptimal.com/blog/2013/01/20/elegant-n-gram-generation-in-python/):

from nltk.util import ngrams as nltkngram
import this, time

def zipngram(text,n=2):
  return zip(*[text.split()[i:] for i in range(n)])

text = this.s

start = time.time()
nltkngram(text.split(), n=2)
print time.time() - start

start = time.time()
zipngram(text, n=2)
print time.time() - start

[out]

0.000213146209717
6.50882720947e-05

在 python 中是否有更快的生成 ngram 的实现?


一些分析的尝试。我认为使用发电机可以提高这里的速度。但与原版的轻微修改相比,改进并不明显。但如果您不需要同时获得完整列表,则生成器函数应该更快。

import timeit
from itertools import tee, izip, islice

def isplit(source, sep):
    sepsize = len(sep)
    start = 0
    while True:
        idx = source.find(sep, start)
        if idx == -1:
            yield source[start:]
            return
        yield source[start:idx]
        start = idx + sepsize

def pairwise(iterable, n=2):
    return izip(*(islice(it, pos, None) for pos, it in enumerate(tee(iterable, n))))

def zipngram(text, n=2):
    return zip(*[text.split()[i:] for i in range(n)])

def zipngram2(text, n=2):
    words = text.split()
    return pairwise(words, n)


def zipngram3(text, n=2):
    words = text.split()
    return zip(*[words[i:] for i in range(n)])

def zipngram4(text, n=2):
    words = isplit(text, ' ')
    return pairwise(words, n)


s = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
s = s * 10 ** 3

res = []
for n in range(15):

    a = timeit.timeit('zipngram(s, n)', 'from __main__ import zipngram, s, n', number=100)
    b = timeit.timeit('list(zipngram2(s, n))', 'from __main__ import zipngram2, s, n', number=100)
    c = timeit.timeit('zipngram3(s, n)', 'from __main__ import zipngram3, s, n', number=100)
    d = timeit.timeit('list(zipngram4(s, n))', 'from __main__ import zipngram4, s, n', number=100)

    res.append((a, b, c, d))

a, b, c, d = zip(*res)

import matplotlib.pyplot as plt

plt.plot(a, label="zipngram")
plt.plot(b, label="zipngram2")
plt.plot(c, label="zipngram3")
plt.plot(d, label="zipngram4")
plt.legend(loc=0)
plt.show()

对于此测试数据,zipngram2 和 zipngram3 似乎是最快的,并且遥遥领先。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 python 中快速/优化 N-gram 实现 的相关文章

随机推荐

  • 选择列表中最早的条目

    如果我有一个包含人员姓名和日期的列表 并且我只想保留每个人最早日期的条目 我该怎么做 我希望最终列表按姓氏字母顺序排列 然后是名字 并且仅包含末尾日期最早的条目 这是列表和我尝试过的示例 但它只是再次给了我相同的列表 L1 Smith Jo
  • Mongoose:Coffeescript 中的递归嵌入文档

    基于这个例子 https github com LearnBoost mongoose blob master examples schema js 有效 var Comment new Schema Comment add title t
  • 禁用 JFrame 中的背景绘制以正确显示 Aero (DWM) 效果

    我在 Java Windows 上使用 Windows Vista 7 的 DWM 功能时遇到问题 我想让我的框架背景使用 Aero 风格 执行此操作的 Windows API 由函数提供DwmExtendFrameIntoClientAr
  • 播放音频 iOS Objective-C

    我正在尝试在我的 iOS 应用程序中播放音频文件 这是我当前的代码 NSString soundFilePath NSString stringWithFormat test m4a NSBundle mainBundle resource
  • 如何在 iOS 7 中让 NSTimer 在后台运行超过 180 秒?

    我已经尝试过 但在 iOS 7 和 Xcode 4 6 2 中工作时间不超过 180 秒 请帮我 UIBackgroundTaskIdentifier bgTask UIBackgroundTaskInvalid UIApplication
  • 存储对相机胶卷图像的引用 - Swift 4

    我有一个非常简单的要求 但显然超出了我的能力范围 我想做的就是允许用户从相机胶卷中选择图像 然后在我的应用程序中存储对该图像的 引用 然后 我可以在需要时从相机胶卷中加载图像 我不想复制图像并将其保存在其他地方 因为我觉得这会浪费手机上的空
  • 如何为 Go 服务器应用程序设置 Let's Encrypt

    我有自己的域 其中包含用 Go 编写的 Web 服务 我使用内置的 Go Web 服务器 前面没有 Nginx 或 Apache 我想开始通过 HTTPS 提供服务 并且我意识到 Let s Encrypt 即将成为实现这一目标的方法 谁能
  • 为什么 C++17 中的全局内联变量和静态内联成员需要防护?

    从 C 17 开始 可以使用以下命令初始化标头中的全局变量和静态成员inline关键词 虽然我理解为什么函数中的静态变量需要受到保护 因为即使在多线程上下文中初始化也应该只发生一次 但我不明白为什么这些新的内联变量也受到保护 您可以在这里看
  • 使用实体框架数据模型添加验证属性

    前言 2015 年 2 月如果您仍在使用实体框架 EDMX 请帮自己一个忙 并使用实体框架代码优先进行结账 不同之处在于 您的表是从模型类创建的 而不是在 EDMX 中 模型类是使用表创建的 这是一个更简单的解决方案 而且这个问题中的问题甚
  • 如何从exe中找出目标框架名称和版本?

    我有一些使用 net Framework 4 5 或 net core 2 1 或 net core 3 1 创建的 exe 文件 我想仅使用 C 应用程序从此 DLL 获取框架名称和版本信息 我在下面编写了一段代码 该代码非常有用 并且适
  • 使用 Nodejs 和 Express 进行视频流传输

    我正在尝试使用nodejs 和express 将视频流式传输到html5 视频播放器 据我所知 很多人以前都这样做过 但是很少有人使用过express 在我发现的情况下 大多数人说这样做 var express require expres
  • EBCDIC 十六进制字符串的 Python 字节表示

    我有一个十六进制字符串 Hex E388854083969497A4A38599408881A2409985829696A38584408699969440814082A48783888583924B 作为字节对象 它看起来像这样 b xe
  • 如何将 Char 转换为 Int?

    所以我有一个String看起来像的整数 82389235 但我想迭代它以将每个数字单独添加到MutableList 然而 当我按照我认为的方式处理它时 var text 82389235 for num in text numbers ad
  • JavaScript 中的“name”关键字是什么?

    当我输入这段看似无辜的代码片段时 values name gedit 突出显示name作为关键字 然而 name未由链接到的页面列出关于保留关键字问题的答案 https stackoverflow com questions 26255 r
  • 检查文件中是否存在一行

    如何检查文件中是否存在一行 如果该行不存在 我还想将该行写入该文件 这是我目前的尝试 logfile open ip log a while 1 line logfile readline line replace n print line
  • 定义派生类型数组

    我正在尝试使用参数声明初始化派生类型 当我编译时 出现以下错误 1 处的 INTEGER 4 数组构造函数中的元素是 CHARACTER 1 用户定义的种类值ip and dp被发现于fasst global 他们是 integer par
  • WCF服务超时

    我有一个公开 wcf 服务的插件 如果我使用 WCStorm 测试此服务 一切正常 我立即得到答复 当我尝试使用加载插件的应用程序中的服务时 我会超时 ProgrammingMaster ServiceClient aClient new
  • 类型错误:中间件不是函数

    我正在尝试在我的reactjs 应用程序中应用redux 由于这些错误 我无法继续 我确信我已经安装了我需要的所有依赖项 这是我的 package json 的相关部分 dependencies react redux 5 0 6 redu
  • 安装其他package.json依赖项

    简单的问题 是否可以在 package json 中引用另一个 package json 并安装其依赖项 谢谢 是的 这是可能的 并且这是由以下自动完成的npm install 如果你有pkg a这取决于pkg b 包括pkg a在您的依赖
  • 在 python 中快速/优化 N-gram 实现

    python 中哪种 ngram 实现速度最快 我试图分析 nltk 与 scott 的 zip http locallyoptimal com blog 2013 01 20 elegant n gram Generation in py