Python程序设计例题

例一:蒙特卡罗方法求解 π 值

 1 from random import random
 2 from math import sqrt
 3 from time import clock
 4 DARTS=1000
 5 hits=0.0
 6 clock()
 7 for i in range(1,DARTS+1):
 8     x,y=random(),random()
 9     dist=sqrt(x**2+y**2)
10     if dist<=1.0:
11         hits=hits+1
12 pi=4*(hits/DARTS)
13 print("pi值是{}.".format(pi))
14 print("运行时间是:{:5.5}s".format(clock()))

运行结果:pi值是3.216.

     运行时间是:0.0034431s
                 [Finished in 0.5s]

例二:贵阳天气:

原文:https://blog.csdn.net/weixin_42358077/article/details/95188483

import requests
from bs4 import BeautifulSoup
import re

def get_page(url):
    try:
        kv = {'user-agent':'Mozilla/5.0'}
        r = requests.get(url,headers = kv)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except:
        return '错误'

def parse_page(html, return_list):
    soup = BeautifulSoup(html, 'html.parser')
    day_list = soup.find('ul', 't clearfix').find_all('li')
    for day in day_list:
        date = day.find('h1').get_text()
        wea = day.find('p',  'wea').get_text()
        if day.find('p', 'tem').find('span'):
                hightem = day.find('p', 'tem').find('span').get_text()
        else:
                hightem = ''
        lowtem = day.find('p', 'tem').find('i').get_text() 
   
        win = re.findall('(?<= title=").*?(?=")', str(day.find('p','win').find('em')))
        wind = '-'.join(win)
        level = day.find('p', 'win').find('i').get_text()
        return_list.append([date, wea, lowtem, hightem, wind, level])
    #return return_list

def print_res(return_list):
    tplt = '{0:<10}\t{1:^10}\t{2:^10}\t{3:{6}^10}\t{4:{6}^10}\t{5:{6}^5}'
    print(tplt.format('日期', '天气', '最低温', '最高温', '风向', '风力',chr(12288)))
    for i in return_list:
        print(tplt.format(i[0], i[1],i[2],i[3],i[4],i[5],chr(12288)))

def main():
    url = 'http://www.weather.com.cn/weather/101260101.shtml'
    html = get_page(url)
    wea_list = []
    parse_page(html, wea_list)
    print_res(wea_list)

if __name__ == '__main__':
    main()

  运行结果:

 

 例三:输出标题:

1 import requests
2 from bs4 import BeautifulSoup
3 r=requests.get('http://www.baidu.com')
4 r.encoding=None
5 result=r.text
6 bs=BeautifulSoup(result,'html.parser')
7 print(bs.title.text)

运行结果:

百度一下,你就知道
[Finished in 1.6s]

 

 

posted @ 2019-11-07 18:27  Jokerˇ  阅读(...)  评论(... 编辑 收藏