python遍历字符_在Python中一次遍历字符串单词

本文介绍了在Python中遍历字符串单词的三种不同方法:标准分割、正则表达式和cStringIO。通过示例代码展示了每种方法的时间性能,并提供了逐行解析文件内容的实现。
摘要由CSDN通过智能技术生成

逐字逐句地遍历文件内容(在我的例子中,是来自古腾堡项目的Oz向导),有三种不同的方式:from __future__ import with_statement

import time

import re

from cStringIO import StringIO

def 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): pass

for word in word_iter_re(woo): pass

for word in word_iter_stringio(woo): pass

导致:% python /tmp/junk.py

iter_std took 0.016321 seconds

iter_re took 0.028345 seconds

iter_io took 0.016230 seconds

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值