栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在Python中一次遍历String单词

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在Python中一次遍历String单词

通过三种不同的方式逐字逐字地遍历文件的内容(以古腾堡计划的《绿野仙踪》为例):

from __future__ import with_statementimport timeimport refrom cStringIO import StringIOdef word_iter_std(filename):    start = time.time()    with open(filename) as f:        for line in f: for word in line.split():     yield word    print 'iter_std took %0.6f seconds' % (time.time() - start)def word_iter_re(filename):    start = time.time()    with open(filename) as f:        txt = f.read()    for word in re.finditer('w+', txt):        yield word    print 'iter_re took %0.6f seconds' % (time.time() - start)def word_iter_stringio(filename):    start = time.time()    with open(filename) as f:        io = StringIO(f.read())    for line in io:        for word in line.split(): yield word    print 'iter_io took %0.6f seconds' % (time.time() - start)woo = '/tmp/woo.txt'for word in word_iter_std(woo): passfor word in word_iter_re(woo): passfor word in word_iter_stringio(woo): pass

导致:

% python /tmp/junk.pyiter_std took 0.016321 secondsiter_re took 0.028345 secondsiter_io took 0.016230 seconds


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/646578.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号