当前位置:编程学习 > 网站相关 >>

Python文本处理(2)

访问子字符串(获取记录中某些字段的数据)
解决方法:
切片,但只能取得一个字段 
[python] 
theline='I Love Python'  
afield=theline[2:6]  
print afield  
  
结果  
Love  
如果需要考虑字段的长度,使用struct.unpack 
[python]  
# -*- coding:gb2312 -*-  
import struct  
baseformat='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个字节一组的数据,使用带有列表推导式的切片方法 
[python]  
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']  
 
替换字符串中的子串
解决方案: 
[python]  
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类来完成该任务 
[python]  
# -*- 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 5  
this is test  
this is 5  
this is test  
在Python2.3中,可以采用如下的方法: 
[python]  
# -*- coding:gb2312 -*-  
old_style='this is %(thing)s'  
#标识符被放在括号中,需要使用%操作符,右边放上字典  
print old_style % {'thing':5}  
print old_style % {'thing':'test'}  
该方法在Python2.4中同样可以使用,但简洁程度不如新的方法
 
补充:Web开发 , Python ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,