Python 函數習題

來源:互聯網
上載者:User

標籤:std   http   split   刪除   join   url   python   nbsp   query   

#encoding=utf-8from urllib.request import urlopenimport randomimport os‘‘‘1. 定義一個fuc(url, folder_path)        擷取url地址的內容,儲存到folder_path的檔案目錄下,並隨機產生一個檔案名稱。‘‘‘def save_url_content(url,folder_path=None):    if not (url.startswith(‘http://‘) or url.startswith(‘https://‘) ):        return u‘url地址不符合規格‘    if not os.path.isdir(folder_path):        return u‘folder_path非檔案夾‘    d = urlopen(url)    content = d.read()    rand_filename = ‘test_%s‘%random.randint(1,1000)    file_path = os.path.join(folder_path,rand_filename)    d = open(file_path,‘wb‘)    d.write(content)    d.close()    return file_pathprint (save_url_content(‘http://www.baidu.com‘,‘tmp‘))‘‘‘3. 定義一個func(url),分析該url內容裡有多少個連結。  ‘‘‘def get_url_count(url):    if not (url.startswith(‘http://‘) or url.startswith(‘https://‘) ):        return u‘url地址不符合規格‘    d = urllib.urlopen(url)    content = d.read()    return len(content.split(‘<a href=‘)) - 1         # str 到bytes 而精緻沒解決print (get_url_count(‘http://hi.baidu.com/jxq61/item/149d29cc8d52513d4594168f‘))‘‘‘2. 定義一個func(folder_path),合并該目錄下的所有檔案,產生一個all.txt。‘‘‘def merge(folder_path):    if not os.path.exists(folder_path):        return ‘not exists‘    for f in os.listdir(folder_path):        file_path = os.path.join(folder_path,f)        if os.path.isdir(file_path):            merge(file_path)        else:            merge_file = open(‘merge_test‘,‘ab+‘)            content = open(file_path,‘rb‘).read()            merge_file.write(content)            merge_file.close()merge(‘tmp‘)‘‘‘4. 定義一個func(url), 擷取他?後的參數,並返回成一個dict。‘‘‘import urlparse#  urlparse模組主要是把url拆分為6部分,並返回元組。#  urllib.parse.urlparse(urlstring, scheme=‘‘, allow_fragments=True)def qs(url):    query = urlparse.urlparse(url).query    return dict([(k,v[0]) for k,v in urlparse.parse_qs(query).items()])print (qs(‘http://126.com‘))print (qs(‘http://api/api?f=5&g=6&y=5‘))print (qs(‘http://api/api?11=53‘))


‘‘‘5. 定義一個func(folder),刪除該folder下的所有檔案。50421  ‘‘‘

#使用遞迴去解決def delete(folder_path):##習題5 if not os.path.exists(folder_path): return ‘not exists‘ for f in os.listdir(folder_path): file_path = os.path.join(folder_path,f) if os.path.isdir(file_path): delete(file_path) else: os.remove(file_path)delete(‘/tmp/5‘)

 

Python 函數習題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.