平時工做中常常須要用到這些python小技巧,順便作個記錄
import requests import time def get_pr(domain): pr = 6 time.sleep(1) html = requests.get("http://pr.web3389.com/pr/%s" % domain.strip()) string = html.text key = "images/pr1/Rank_" ipos = string.find(key) pr = string[ipos+ len(key):] pr = pr[:1] try: if int(pr) < 5: pr = 5 except: pr = 5 n = int(pr) - 4 tmp = 10 * 10**(n) count = tmp + count with open('domain_date.txt') as f: for line in f.readlines(): url = line.split(' ')[0] month = line.split(' ')[-1].split('-')[1] try: pr = get_pr(url) except: pass print(pr,url,month) fuck = '{}:{}:{}'.format(url,month,pr) with open('new_domain.txt','a') as file: file.writelines(fuck + ‘\n’)
對字典value進行排序 import operator diaosi = {} with open('all.txt', 'r', encoding="utf-8") as f: for line in f.readlines(): country = line.split(':')[0] pr_value = int(line.split(':')[-1].lstrip().strip()) print(country) diaosi.update({country: pr_value}) sorted_x = sorted(diaosi.items(), key=operator.itemgetter(1), reverse=True) with open('fuck.txt', 'a+', encoding="utf-8") as file: for line in sorted_x: file.writelines(line[0] + ':' + str(line[1]) + '\n') 對字典key進行排序: sorted_x = sorted(diaosi.items(), key=operator.itemgetter(0))
對keys存在的,對value進行相加 with open('new_domain.txt') as f: diaosi = {} for line in f.readlines(): month = int(line.split(':')[1]) pr = line.split(':')[-1].strip() value = int(diaosi.get(str(month), "0")) + int(pr) diaosi.update({str(month): value}) print(diaosi)
def has_primary_key(): for row in rows: if row[1] == 0 and row[9] != 'YES': return True return False 很是的簡單,可是,若是咱們使用any函數的話,代碼將會更短。以下所示: def has_primary_key(): return any(row[1] == 0 and row[9] != 'YES' for row in rows):
剛開始學Python時候幫同事寫的一個需求,這幾天看看pythonic果真還有更好的寫法 # 以長度爲統計分別放入不一樣的列表中 for url in urls: url_len = str(len(url)) if url_len in url_list: url_list[url_len].append(url) else: url_list[url_len] = [url] defaultdict實現: d = defaultdict(list) for key, value in pairs: d[key].append(value)
去重複,不改變順序: l1 = ['b','c','d','b','c','a','a'] l2 = sorted(set(l1),key=l1.index) print l2 奇技淫巧倒算不上,有些時候確實是挺有用的! list_ = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] 把list_合併爲[1, 2, 3, 4, 5, 6, 7, 8, 9] [k for i in list_ for k in i] 能夠這樣: items = [1, 2, 3, 4, 5] squared = list(map(lambda x: x**2, items))
#coding:utf-8 for line in range(1,255): with open('1.txt','a') as f: f.writelines('192.168.128.{}'.format(line)+'\n')