Coursera零基础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
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可变列表
fname = raw_input("Enter file name: ")
fh = open(fname)
lst = list()
splice破解版
words = list()
for line in fh:
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()
y = 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:...')
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')
excel vlookup公式及用法sum=0
for tag in tags:
sum=sum+ts[0])
print sum
11、urllib⽹页读取
import urllib
from BeautifulSoup import *
js数组去重复合并插件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
serviceurl = 'python-data.dr-chuck/geojson?'
while True:
address = raw_input('Enter location: ')
if len(address) < 1 : break
url = serviceurl + urllib.urlencode({'sensor':'false', '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, ) )
else :
(org, ))
connmit()
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.close()
16、sqlite3数据库操作企业网站模板建站流程
ElementTree as ET
python入门教程2import sqlite3
conn = t('trackdb.sqlite')
cur = conn.cursor()
DROP 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,
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论