python uuid生成唯一id
uuid是128位的全局唯一标识符(univeral unique identifier),通常用32位的一个字符串的形式来表现。
uuid.uuid1()是基于MAC地址,时间戳,随机数来生成唯一的uuid,可以保证全球范围内的唯一性。
#coding=utf-8
import uuid
random_id = uuid.uuid1()
print(random_id)
python解决unicode编码显示中文
在做python爬虫的时候经常会遇到一个问题,str类型的unicode字符串转成中文的问题,
在做爬虫的时候,爬下来如下一段代码'\u9999\u6e2f\u5e9f\u9752\u60f3\u62d6',这是unicode编码,需要将它解析成中文,尝试了网上许多种方法,(先编码再解码),都不行。其实直接print出来就是中文,那么为什么之前不行呢,因为之前爬下来的是一段话包含这段乱码,如果只是这段乱码是可以的
strhtml = '\u9999\u6e2f\u5e9f\u9752\u60f3\u62d6\u6fb3\u95e8\u4e0b\u6c34\uff0c\u88ab\u6fb3\u95e8\u540c\u80de\u62d2\u7edd\u4e86'
print(strhtml)
new_strhtml = strhtml.replace("\\u","\\\\u") #将\u替换为\\u
print(new_strhtml)
python替换字符串中的反斜杠\
s = '\\'
result = s.replace('\\', '\\\\')
print(result)
Python中JSON格式与字符串转换
参考:https://blog.youkuaiyun.com/qq_38038143/article/details/80832157
import json
origin_str = '''
[
{"name": "张三","gender": "男"},
{"name": "赵四","gender": "男"},
{"name": "王五","gender": "女"}
]
'''
#将字符串转为json格式
result = json.loads(origin_str)
print(type(result))
print(result)
print(result[0].get("name"))
python下载保存http图片
import os,stat
import urllib.request
img_url="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1516371301&di=d99af0828bb301fea27c2149a7070" \
"d44&imgtype=jpg&er=1&src=http%3A%2F%2Fupload.qianhuaweb.com%2F2017%2F0718%2F1500369506683.jpg"
dir_path='D:/book/img'
file_name ="pyt"
try:
#是否有这个路径
if not os.path.exists(dir_path):
#创建路径
os.makedirs(dir_path)
#获得图片后缀
file_suffix = os.path.splitext(img_url)[1]
print(file_suffix)
#拼接图片名(包含路径)
local_imgPath = '{}{}{}{}'.format(dir_path,os.sep,file_name,file_suffix)
print(filename)
#下载图片,并保存到文件夹中
urllib.request.urlretrieve(img_url,local_imgPath)
except IOError as e:
print("IOError")
except Exception as e:
print("Exception")
python random模块从list中随机选择
# choice方法随机选择某个元素
from random import choice
foo = ['a', 'b', 'c', 'd', 'e']
print(choice(foo))
# sample函数从列表中随机选择一组元素
list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
slice = random.sample(list, 5) #从list中随机获取5个元素,作为一个片断返回
print(slice)
python 中tuple(元组)、list(列表)区别
一、元组定义
元组和列表类似,元组使用的是小括号,列表是中括号,但是元组不像列表那样可以增删改;
如果元组中存在列表或字符串,那么可以对其进行修改。
# 创建空元组
tuple = (1,2,3,4,5)
# 创建空列表
list = [1,2,3,4,5]
python中使用pymysql往mysql数据库中更新(update)数据
from pymysql import *
def main():
# 创建connection连接
conn = connect(host='', port=3306, database='', user='',password='', charset='utf8')
# 获取cursor对象
cs1 = conn.cursor()
# 执行sql语句
# update_sql = "update 表名 set 字段1 = 值1 where 字段2 = '{}'".format(值2)
update_sql = 'UPDATE science SET labels = "{}" WHERE uuid = "{}"'.format("news", "123")
cs1.execute(query)
# 提交之前的操作,如果之前已经执行多次的execute,那么就都进行提交
conn.commit()
# 关闭cursor对象
cs1.close()
# 关闭connection对象
conn.close()
if __name__ == '__main__':
main()