Python文本处理(2)

来源:互联网 发布:windows update安装慢 编辑:程序博客网 时间:2024/05/23 01:13

访问子字符串(获取记录中某些字段的数据)

解决方法:

切片,但只能取得一个字段 

theline='I Love Python'afield=theline[2:6]print afield结果Love
如果需要考虑字段的长度,使用struct.unpack 
# -*- coding:gb2312 -*-import structbaseformat='1s 6x 6s'#首先,baseformat制定了该如何对字符串进行分组,x代表跳过,s代表取出#所以上面的代码表示拿走1个字符,跳过6个字符,拿走6个字符theline='I Love Python So Much'numremain=len(theline)-struct.calcsize(baseformat)#当然,theline的字符串的长度要大于6+6+1的长度,所以需要计算剩余还有多少字符串format='%s %ds' %(baseformat,numremain)#重新进行分组,现在就包括了最后剩余的那部分字符串l,s1,s2=struct.unpack(format,theline)#用format和theline就可以进行unpack操作了print l,s1,s2
如果想要获得5个字节一组的数据,使用带有列表推导式的切片方法 
theline='I Love Python So Much'fivers=[theline[k:k+5] for k in xrange(0,len(theline),5)]print fivers结果['I Lov', 'e Pyt', 'hon S', 'o Muc', 'h']


替换字符串中的子串

解决方案: 

def expand(format, d, marker='"', safe=False):    if safe:        def lookup(w): return d.get(w, w.join(marker*2))    else:        def lookup(w): return d[w]    parts = format.split(marker)    parts[1::2] = map(lookup, parts[1::2])    return ''.join(parts)if __name__ == '__main__':    print expand('just "a" test', {'a': 'one'})

在Python2.4以后,可以采用string.Template类来完成该任务 

# -*- coding:gb2312 -*-import string#从字符串生成模板,其中标识符被$标记new_style=string.Template('this is $thing')#给模板的substitute方法传入一个字典参数print new_style.substitute({'thing':5})print new_style.substitute({'thing':'test'})#也可以传递关键字参数print new_style.substitute(thing=5)print new_style.substitute(thing='test')结果this is 5this is testthis is 5this is test

在Python2.3中,可以采用如下的方法: 

# -*- coding:gb2312 -*-old_style='this is %(thing)s'#标识符被放在括号中,需要使用%操作符,右边放上字典print old_style % {'thing':5}print old_style % {'thing':'test'}
该方法在Python2.4中同样可以使用,但简洁程度不如新的方法







原创粉丝点击