Courra零基础Python入门系列课程习题解答

更新时间:2023-06-18 02:33:26 阅读: 评论:0

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,

本文发布于:2023-06-18 02:33:26,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/fan/90/148871.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:开始   解答   习题   可变   建设   数据库
相关文章
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图