Python基础学习之路(二)

十二、         图形界面
1.      介绍
wxPython 基于wxWindows,跨平台
Tkinter  Tk平台
PythonWin windows平台
Java Swing  只能用Jython
PyGTK  GTK平台

PyQt   Qt平台,跨平台

2.      官方帮助文档:
wxpython   Http://wxpython.org
Tkinter  http://wiki.python.org/moin/TkInter
PythonWin  http://starship.python.net/crew/mhammond
Java Swing http://java.sum.com/docs/books/tutorial/uiswing
PyGTK  http://pygtk.org
PyQt   http://wiki.python.org/moin/PyQt
3.      实践:
4.      代码:
5.      遇到问题处理:

wxPython库安装

报错:



错误原因:
解决:
6.      小结:
GUI
Python的GUI平台
wxPython
布局
事件处理

十三、         数据库支持
1.      介绍
Sqlite  pysqlite
2.      官方帮助文档:
3.      实践:
4.      代码:
Importdata.py文件
import sqlite3
def convert(value):
    if value.startwith('~'):
        return value.strip('~')
    if not value:
        value = '0'

        return float(value)

conn=sqlite3.connect('food.db')
curs=conn.cursor()

create_tab='''
create table food (
id text  primary key,
desc text,
water float,
kcal float,
protein float,
fat float,
ash float,
carbs float,
fiber float,
sugar float
)
'''
curs.execute(create_tab)
query='insert into food values(?,?,?,?,?,?,?,?,?,?)'
for line in open('ABBREV.txt'):
    fields = line.split('^')
    #field_count=fields.count()
    vals = [convert(f) for f in fields[:10]]
    curs.execute(query, vals)
conn.commit()

conn.close()

food_query.py文件
import sqlite3, sys
conn=sqlite3.connect('food.db')
curs=conn.cursor()
query='select * from food where %s' % sys.argv[1]
print(query)

curs.execute(query)
names=[f[0] for f in curs.description]
for row in curs.fetchall():
for pair in zip(names,row):
print '%s: %s' % pair
print

5.      遇到问题处理:
Pysqlite库 安装报错:
src/connection.h:26:20: fatal error: Python.h: No such file or directory
原因:缺少python 开发环境
解决:
For apt (Ubuntu, Debian...):
sudo apt-get install python-dev   # for python2.x installs
sudo apt-get install python3-dev  # for python3.x installs
For yum (CentOS, RHEL...):
sudo yum install python-devel
For dnf (Fedora...):
sudo dnf install python2-devel  # for python2.x installs
sudo dnf install python3-devel  # for python3.x installs
For zypper (openSUSE...):
sudo zypper in python-devel   # for python2.x installs

sudo zypper in python3-devel  # for python3.x installs

6.      小结:
Python数据库变成接口
连接
游标
类型和特殊值
SQLite
函数:
Connect(…)

十四、         网络编程
1.      介绍
2.      官方帮助文档:
3.      实践:

实验1:


实验1代码:
Myserver1.py文件
import socket
s=socket.socket()
host='localhost'
print('hostname:'+host)
port =8888
s.bind((host, port))
s.listen(5)
while True:
    c, addr=s.accept()
    print 'Got connect from ',addr
    c.send('connected')
c.close()

myclient.py文件
import socket
s=socket.socket()
host='localhost'
port=8888
s.connect((host,port))
print s.recv(1024)

实验2:


>>> from urllib import urlopen
>>> webpage=urlopen('http://www.python.org')
>>> import re
>>> text=webpage.read()
>>> m=re.search('<a href="([^"]+)" .*?>about</a>', text, re.IGNORECASE)
>>> m.group(1)
'/about/'

>>> file=urlopen('file:/home/shilei/PycharmProjects/untitled2/log.log')
>>> text = file.read()
>>> text.strip()

'2018-01-11 14:55:09 PM - root - DEBUG -<input>:  debug\n2018-01-11 14:55:09 PM - root - INFO -<input>:  info\n2018-01-11 14:55:09 PM - root - WARNING -<input>:  warning\n2018-01-11 14:55:09 PM - root - ERROR -<input>:  error\n2018-01-11 14:55:09 PM - root - CRITICAL -<input>:  critical\n2018-01-11 14:55:09 PM - root - DEBUG -<input>:  log'

实验3:


实验4:



实验5:


Myserver_select.py文件
import socket, select
s=socket.socket()
host='localhost'
print('hostname:'+host)
port =8888
s.bind((host, port))
s.listen(5)
inputs = [s]
while True:
    rs, ws, es = select.select(inputs, [], [])
    for r in rs:
        if r is s:
            client_channel, addr = s.accept()
            print 'Got connect from ', addr
            inputs.append(client_channel)
           client_channel.send('connected server')
        else:
            try:
                data=r.recv(1024)
               disconnected = not data
            except socket.error:
                disconnected = True
            if disconnected:
                print r.getpeername(), 'disconnected'
                inputs.remove(r)
            else:

                print data

myclient.py文件
import socket,random
s=socket.socket()
host='localhost'
port=8888
s.connect((host,port))
n=random.randrange(1,10)
s.send('client:'+str(n))
print 'client:'+str(n)

print s.recv(1024)

try:
    while True:
        cmd=raw_input('enter quit(Q) send(S):')
        cmd=cmd.strip().lower()
        if cmd=='s':
            s.send('I am '+str(n))
        elif cmd=='q':
            s.close()
            break
except:
s.close()
 

实验6:

MyHTMLParser.py文件
from urllib import urlopen
from HTMLParser import HTMLParser

class Scraper(HTMLParser):
    in_h3=False
    in_link=False
    def handle_starttag(self, tag, attrs):
        attrs = dict(attrs)
        if tag=='h3':
            self.in_h3=True
        if tag=='a' and 'href' in attrs:
            self.in_link=True
            self.chunks=[]
            self.url=attrs['href']

    def handle_data(self, data):
        if self.in_link:

            self.chunks.append(data)

    def handle_endtag(self, tag):
        if tag=='h3':
           self.in_h3=False
        if tag=='a':
           # if self.in_h3 and self.in_link:
             if self.in_link:
                print '%s (%s)' %(''.join(self.chunks), self.url)
                #print('%(a) (%(b))').format({'a':''.join(self.chunks),'b':self.url})
def test():
    text=urlopen('http://www.python.org/community/jobs').read()
    parser=Scraper()
    parser.feed(text)
    parser.close()

if __name__=='__main__':

test()


实验7:


myBeautifulSoup.py文件:
from urllib import urlopen
from BeautifulSoup import BeautifulSoup

text=urlopen('http://www.python.org/community/jobs').read()
soup=BeautifulSoup(text)
jobs=set()
for header in soup('a'):
    links=header('a','href')
    if not links: continue
    link=links[0]
    jobs.add('%s (%s)' %(link.string, link['href']))
print '\n'.join(sorted(jobs,key=lambda s: s.lower()))

4.      遇到问题处理:

5.      小结:

十五、         Python web
十六、         测试
1.      官方帮助文档:
2.      实践:

实验1:

My_math.py文件
def square(x,y):
return x*y

MytestCase.py 文件
import unittest, my_math
class MytestCase(unittest.TestCase):
    def testInteger(self):
        for x in xrange(-10,10):
            for y in xrange(-10,10):
                p=my_math.square(x,y)
                self.failUnless(p == x*y,'testInteger failed')

    def testFloats(self):
        for x in xrange(-10,10):
            for y in xrange(-10,10):
                x=x/10.0
                y=y/10.0
                p=my_math.square(x,y)
                self.failUnless(p == x*y,'testFloats failed')

if __name__=='__main__':

    unittest.main()

3.      代码:
4.      遇到问题处理:
5.      小结:

 
十七、         扩展Python
十八、         打包
1.      官方帮助文档:
2.      实践:

实践1:




3.      代码:
4.      遇到问题处理:
5.      小结:


十九、         日志记录
1.      官方帮助文档:
2.      实践:

实验1;

MyReadConfig.py文件
from ConfigParser import ConfigParser
CONFIGFILE='python.txt'
config=ConfigParser()
config.read(CONFIGFILE)
print config.get('message','greeting')
radius=input(config.get('message','question')+'')
print config.get('message','result_message')
print config.getfloat('numbers','pi')*radius**2


python.txt文件
[numbers]
pi:3.141592653589793
[message]
greeting:program
question:input radius?
result_message:this area is

实践2:



Mylogging.py文件
import logging
logging.basicConfig(level=logging.INFO, filename='mylog.log')
logging.info('Start program')
logging.info('Trying to divide 1 by 0')
print 1/1
logging.info('The divide succeed')
logging.info('end')

3.      代码:
4.      遇到问题处理:

5.      小结:


=================================================================
参考文献
《Python 基础教程(第2版.修订版)》 作者【挪】Magnus Lie Hetland
=================================================================

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值