Courra零基础Python⼊门系列课程习题解答Chapter7 开始的答案,兹以⼴⼤⽹友参考
1、files读取本地⽂件
fname = raw_input("Enter file name: ")
fh = open(fname)
for line in fh:
print line.strip().upper()
2、files读取本地⽂件
fname = raw_input("Enter file name: ")
fh = open(fname)
add = 0
count=0
ccrs
for line in fh:
if not line.startswith("X-DSPAM-Confidence:") :
continue
num = line.find(":")
add = add+float(line[num+1:])
count=count+1
print "Average spam confidence:",add/count
3、lists可变列表
loading是什么意思fname = raw_input("Enter file name: ")
fh = open(fname)
lst = list()
words = list()
for line in fh:
romingo
words = line.split()
for word in words:
unt(word)==0:
lst.append(word)
lst.sort()
print lst
4、lists可变列表
fname = raw_input("Enter file name: ")
if len(fname) < 1 : fname = ""
fh = open(fname)
count = 0
lst =list()
for line in fh:
if line.startswith("From "):
lst = line.split()
print lst[1]
count=count+1
print "There were", count, "lines in the file with From as the first word"
5、dict字典
name = raw_input("Enter file:")
if len(name) < 1 : name = ""
handle = open(name)
words=list()
icount=dict()
for line in handle:
if line.startswith("From "):
words=line.split()
word=words[1]
icount[word]=(word,0)+1
maxkey=""
maxvalue=0
for ikey,ivalue in icount.items():
if ivalue > maxvalue:
maxkey=ikey
maxvalue=ivalue
print maxkey,maxvalue
6、dict字典
name = raw_input("Enter file:")
if len(name) < 1 : name = ""
handle = open(name)
icount=dict()
ilist=list()
for line in handle:
if line.startswith("From "):
words=line.split()
word=words[5]
words=word.split(":")
word=words[0]
icount[word]=(word,0)+1
ilist=icount.keys()
ilist.sort()
for sth in ilist:
print sth,icount[sth]
7、re正则表达式
import re
handle = open("regex_")
ad()
ulandy = re.findall('[0-9]+', lines)
sum=0
for word in y:
sum=int(word)+sum
print sum
8、urllib⽹页读取
import urllib
fhand=urllib.urlopen('http:...')zk
for line in fhand:
print line.strip()
9、urllib⽹页读取
from BeautifulSoup import *
html=urllib.urlopen('http:...').read()
soup = BeautifulSoup(html)
tags=soup('a')
for tag in tags
print'TAG:',tag
print'URL:',('href', None)
print'Contents:',ts[0]
建设工程施工合同
print'Attrs:',tag.attrs
10、urllib⽹页读取
import urllib
from BeautifulSoup import *
html=urllib.urlopen('python-data.dr-chuck/comments_341353.html').read() soup = BeautifulSoup(html)
tags=soup('span')
sum=0
for tag in tags:
sum=sum+ts[0])
print sum
11、urllib⽹页读取
import urllib
from BeautifulSoup import *
url = raw_input('Enter - ')
for i in range(1,8):
html = urllib.urlopen(url).read()
soup = BeautifulSoup(html)
# Retrieve all of the anchor tags
tags = soup('a')
count=1
for tag in tags:
url = ('href', None)
print url
if count==18 :
print'Next'
break
count=count+1
import urllib
ElementTree as ET
url = 'python-data.dr-chuck/l'
print'Retrieving', url奥斯卡最佳影片
uh = urllib.urlopen(url)
data = uh.read()
print'Retrieved',len(data),'characters'
tree = ET.fromstring(data)
results = tree.findall('comments/comment')
icount=len(results)
isum=0
for result in results:
isum += float(result.find('count').text)
print'Count:',icount
print'Sum:',isum
13.json⽂件读取
import json
url = 'python-data.dr-chuck/comments_341354.json'
print 'Retrieving', url
uh = urllib.urlopen(url)
data = uh.read()
print 'Retrieved',len(data),'characters'
info = json.loads(data)
isum=0
for item in info["comments"]:
isum += item["count"]
print 'Count:',len(info["comments"])
print 'Sum:',isum
14、json⽂件读取
import urllib
import json
rviceurl = 'python-data.dr-chuck/geojson?'
while True:
address = raw_input('Enter location: ')
if len(address) < 1 : break
url = rviceurl + urllib.urlencode({'nsor':'fal', 'address': address})
print'Retrieving', url
uh = urllib.urlopen(url)
data = uh.read()
print'Retrieved',len(data),'characters'
try: js = json.loads(str(data))
英语导游欢迎词except: js = None
if'status'not in js or js['status'] != 'OK':
print'==== Failure To Retrieve ===='
print data
continue
print json.dumps(js, indent=4)
plid = js["results"][0]["place_id"]
print'place_id:',plid
15、sqlite数据库操作
conn = t('emaildb.sqlite')
cur = conn.cursor()
DROP TABLE IF EXISTS Counts''')
CREATE TABLE Counts (org TEXT, count INTEGER)''')
fname = raw_input('Enter file name: ')
if ( len(fname) < 1 ) : fname = ''
fh = open(fname)
for line in fh:
if not line.startswith('From: ') : continue
pieces = line.split()
pieces=pieces[1].split("@")
org = pieces[1]
row = cur.fetchone()
if row is None:
VALUES ( ?, 1 )''', ( org, ) )
el :
(org, ))
sqlstr = 'SELECT org, count FROM Counts ORDER BY count DESC LIMIT 10'
print"Counts:"
for row ute(sqlstr) :
print str(row[0]), row[1]
cur.clo()
16、sqlite3数据库操作
ElementTree as ET
import sqlite3
conn = t('trackdb.sqlite')
cur = conn.cursor()
entombedDROP TABLE IF EXISTS Artist;凭吊
DROP TABLE IF EXISTS Album;
DROP TABLE IF EXISTS Track;
DROP TABLE IF EXISTS Genre;
CREATE TABLE Artist (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
name TEXT UNIQUE
);
CREATE TABLE Genre (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
name TEXT UNIQUE
);
CREATE TABLE Album (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
artist_id INTEGER,
title TEXT UNIQUE
);
CREATE TABLE Track (
id INTEGER NOT NULL PRIMARY KEY
AUTOINCREMENT UNIQUE,
title TEXT UNIQUE,