python常见问题解决方案

平时工作中经常需要用到这些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')

  

  

  

 

  

  

posted @ 2016-12-08 10:44  轻落语  阅读(254)  评论(0编辑  收藏  举报