您的位置:首页 > 编程语言 > Python开发

Python Cookbook (1) 文本

2013-03-30 13:05 393 查看
文本啊文本
1. 每个人都同意文本处理很有用。
2. 文本是一串字符,二进制是一串字节。
3. 基本文本操作:
1) 解析数据并将数据放入程序内部的结构中
2) 转成别的形式
3) 生成全新数据
4. 文本的来源
1) 文件
2) 网站
5. 文本应该属于应用程序层面,二进制属于底层

Example:

#!/usr/local/bin/python
import testlib
import string

#test book <<Python Cookbook>>

def test_string_template():
new_style = string.Template('this is $thing')
print new_style.substitute({'thing':5})
print new_style.substitute({'thing':'test'})
# or
print new_style.substitute(thing=5)
print new_style.substitute(thing='test')

def test_string_unicode():
unicodestr = u"Hello world"
print "unicodestr =", unicodestr
utf8str = unicodestr.encode("utf-8")
print "utf8str =", utf8str
asciistr = unicodestr.encode("ascii")
print "asciistr =", asciistr
plainstr = unicode(utf8str, "utf-8")
print "plainstr =", plainstr

def test_string():
testlib.in_("test_string"); # from testlib write by self
str1="012345"
for s in str1 :
print s, #do_something_with(c)
print "\nstr1="+str1
print "str1[1:3] =", str1[1:3]
print "str1[0] =", str1[0]
print "str1[-2] =", str1[-2]
#list_of_lines = one_large_string.splitlines()
#one_large_string = '\n'.join(list_of_lines)

print "map(ord, 'ciao') =", map(ord, 'ciao')

print 'test center, ljust and rjust:'
print 'center'.center(20,'+')
print '|', 'hej'.ljust(20), '|', 'hej'.rjust(20), '|', 'hej'.center(20), '|'

print 'test lstrip, rstrip and strip:'
str2='    hej     '
print '|', str2.lstrip(), '|', str2.rstrip(), '|', str2.strip(), '|'

print 'test upper, lower, capitalize, title:'
str3='ONe Two tHree'
print "str3 =", str3
print "str3.upper =", str3.upper()
print "str3.lower =", str3.lower()
print "str3.capitalize =", str3.capitalize()
print "str3.title =", str3.title()

test_string_template()
test_string_unicode()

def testGo():
test_string()

if __name__=="__main__" :
testGo()


PS:

testlib.py

#!/usr/local/bin/python

#test tools for all the test

def in_(arg):
print
print arg + " called"
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: