python核心编程(文本处理)

1、csv文件读写

!/usr/bin/env python

import csv
from distutils.log import warn as printf

DATA = (
(9, 'Web Clients and Servers', 'base64, urllib'),
(10, 'Web Programming: CGI & WSGI', 'cgi, time, wsgiref'),
(13, 'Web Services', 'urllib, twython'),
)
printf('***writing csv data')
f=open('bookdata.csv','w')
writer=csv.writer(f)
for record in DATA:
writer.writerow(record)
f.close()

printf('***reading csv data')
f=open('bookdata.csv','r')
reader=csv.reader(f)
for a,b,c in reader:
printf('%s %r %s' %(a,b,c))
f.close()

2、join:

!/usr/bin/python

-- coding: UTF-8 --

str = "-";
seq = ("a", "b", "c"); # 字符串序列
print str.join( seq );

3、zip用法

a = [1,2,3] #此处可迭代对象为列表
b = [4,5,6]
c = [4,5,6,7,8]
zipped = zip(a,b)
zipped
#返回的是一个对象
list(zipped)
[(1, 4), (2, 5), (3, 6)] #使用list()函数转换为列表
list(zip(a,c))
[(1, 4), (2, 5), (3, 6)]
zipped = zip(a,b)
list(zip(*zipped)) #解压也使用list进行转换
[(1, 2, 3), (4, 5, 6)]

4、python字典转json:json.dumps(xx,indent=xx)

!/usr/bin/env python

from distutils.log import warn as printf
from json import dumps
from pprint import pprint

BOOKs = {
'0132269937': {
'title': 'Core Python Programming',
'edition': 2,
'year': 2007,
},
'0132356139': {
'title': 'Python Web Development with Django',
'authors': ['Jeff Forcier', 'Paul Bissex', 'Wesley Chun'],
'year': 2009,
},
'0137143419': {
'title': 'Python Fundamentals',
'year': 2009,
},
}

printf('*** RAW DICT ***')
printf(BOOKs)

printf('\n*** PRETTY_PRINTED DICT ***')
pprint(BOOKs)

printf('\n*** RAW JSON ***')
printf(dumps(BOOKs))

printf('\n*** PRETTY_PRINTED JSON ***')
printf(dumps(BOOKs, indent=4))

5、字典转xml:

!/usr/bin/env python

from xml.etree.ElementTree import Element, SubElement, tostring
from xml.dom.minidom import parseString

BOOKs = {
'0132269937': {
'title': 'Core Python Programming',
'edition': 2,
'year': 2006,
},
'0132356139': {
'title': 'Python Web Development with Django',
'authors': 'Jeff Forcier:Paul Bissex:Wesley Chun',
'year': 2009,
},
'0137143419': {
'title': 'Python Fundamentals',
'year': 2009,
},
}

books = Element('books')
for isbn, info in BOOKs.items():
book = SubElement(books, 'book')
info.setdefault('authors', 'Wesley Chun')
info.setdefault('edition', 1)
for key, val in info.items():
SubElement(book, key).text = ', '.join(str(val).split(':'))

xml = tostring(books)
print('*** RAW XML ***')
print(xml)

print('\n*** PRETTY-PRINTED XML ***')
dom = parseString(xml)
print(dom.toprettyxml(' '))

print('*** FLAT STRUCTURE ***')
for elmt in books.getiterator():
print(elmt.tag, '-', elmt.text)

print('\n*** TITLES ONLY ***')
for book in books.findall('.//title'):
print(book.text)
6、xml-rpc通信:
服务端:

* coding:utf-8 *

from xmlrpc.server import SimpleXMLRPCServer

调用函数

def respon_string(str):
return "get string:%s"%str

if name == 'main':
server = SimpleXMLRPCServer(('localhost', 8888)) # 初始化
server.register_function(respon_string, "get_string") # 注册函数
print ("Listening for Client")
server.serve_forever() # 保持等待调用状态

客户端:

* coding:utf-8 *

from xmlrpc.client import ServerProxy

if name == 'main':
server = ServerProxy("http://localhost:8888") # 初始化服务器
print (server.get_string("cloudox")) # 调用函数并传参

你可能感兴趣的:(python核心编程(文本处理))