By accessing the website and accepting the Cookie Policy, you agree to use the cookies provided by the Site in accordance with to analyze traffic, remember your preferences, and optimize your experience.

分类 - Python

2020-04-10 11:16:58    397    0    0

生成文件

pip freeze > requirements.txt

从requirements.txt安装依赖库

pip install -r requirements.txt

当提示权限不够时,前面加上sudo


2020-04-10 11:03:19    85    0    0

发行版本 v2.18.1. (安装说明)

Requests 唯一的一个非转基因的 Python HTTP 库,人类可以安全享用。

警告:非专业使用其他 HTTP 库会导致危险的副作用,包括:安全缺陷症、冗余代码症、重新发明轮子症、啃文档症、抑郁、头疼、甚至死亡。

看吧,这就是 Requests 的威力:

>>> r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
>>> r.status_code
200
>>> r.headers['content-type']
'application/json; charset=utf8'
>>> r.encoding
'utf-8'
>>> r.text
u'{"type":"User"...'
>>> r.json()
{u'private_gists': 419, u'total_private_repos': 77, ...}

参见 未使用 Requests 的相似代码.

Requests 允许你发送纯天然,植物饲养的 HTTP/1.1 请求,无需手工劳动。你不需要手动为 URL 添加查询字串,也不需要对 POST 数据进行表单编码。Keep-alive 和 HTTP 连接池的功能是 100% 自动化的,一切动力都来自于根植在 Requests 内部的 urllib3

功能特性

Requests 完全满足今日 web 的需求。

  • Keep-Alive & 连接池
  • 国际化域名和 URL
  • 带持久 Cookie 的会话
  • 浏览器式的 SSL 认证
  • 自动内容解码
  • 基本/摘要式的身份认证
  • 优雅的 key/value Cookie
  • 自动解压
  • Unicode 响应体
  • HTTP(S) 代理支持
  • 文件分块上传
  • 流下载
  • 连接超时
  • 分块请求
  • 支持 .netrc

Requests 支持 Python 2.6—2.7以及3.3—3.7,而且能在 PyPy 下完美运行。

2020-04-10 11:00:55    261    0    0

用python下载文件的若干种方法汇总。

0. requests标准模板

import requests
url="******"
try:
    r=requests.get(url)
    r.raise_for_status()  #如果不是200,产生异常requests.HTTPError
    r.encoding=r.apparent_encoding
    print(r.text)
except:
    print("爬取失败...")

1. 下载图片

import requests
url = 'https://www.python.org/static/img/python-logo@2x.png'
myfile = requests.get(url)
open('PythonImage.png', 'wb').write(myfile.content)

wget

import wget
url = "https://www.python.org/static/img/python-logo@2x.png"
wget.download(url, 'pythonLogo.png')

2. 下载重定向的文件

import requests
url = 'https://readthedocs.org/projects/python-guide/downloads/pdf/latest/'
myfile = requests.get(url, allow_redirects=True)
open('hello.pdf', 'wb').write(myfile.content)

3. 分块下载大文件

import requests
url = 'https://buildmedia.readthedocs.org/media/pdf/python-guide/latest/python-guide.pdf'
r = requests.get(url, stream = True)
with open("PythonBook.pdf", "wb") as Pypdf:
    for chunk in r.iter_content(chunk_size = 1024): # 1024 bytes
        if chunk:
            Pyp
json    2020-04-10 10:58:09    348    0    0

文件处理

使用文件可以做数据的持久化(本地化)。 包括数据库文件,txt、json,plist,二进制文件等等。
在python中的文件操作很简单,是通过一个内置函数open()实现的。

"""
open(file, mode='r', encoding=None, errors=None)
open函数主要接收两个参数,需要打开的文件file, 打开方式mode,encoding编码方式,
如果需要忽略少数的如编码之类的错误
可以传入errors="ignore"
w 以写方式打开, 文件不存在时创建新文件
a 以追加模式打开,文件不存在时创建新文件
r+ 以读写模式打开
w+ 以读写模式打开 (参见 w )
a+ 以读写模式打开 (参见 a )
rb 以二进制读模式打开
wb 以二进制写模式打开 (参见 w )
ab 以二进制追加模式打开 (参见 a )
rb+ 以二进制读写模式打开 (参见 r+ )
wb+ 以二进制读写模式打开 (参见 w+ )
ab+ 以二进制读写模式打开 (参见 a+ )
"""
f = open(r"./python招聘信息.txt","r",encoding="utf-8")
f.read() #以字符串的形式,一次性返回所有文件内容
f.readline() # 读一行,调用一次,读取一行
f.readlines() #返回一个列表,列表的元素是文件中每一行的内容
#f.write() 当以写的形式打开文件时,可以使用该方法,需要传入写入的内容
f.flush() #当需要更新文件的内容时,调用该方法刷新缓存,立即将数据写入文件
f.close() #关闭文件,如果需要向文件中写入内容,在没有flush方法时,调用次方法才能将内容写入

json数据转换

json数据本身是文本数据;json文件就是后缀是.json的文件, 并且文件内容必须满足json格式的要求

1.json格式
a.一个json对应一条数据
b.json中的数据必须是json对应的数据类型

数字类型(number) --> 所有的数字,包含整数和小数,例如:100, 12.5
字符串类型(string) --> 用双引号括其的数据,例如:"abc", "你好,世界!"
数组(array) --> 相当于python中列表, 例如: [100, 230, "abc", "你好"]

json    2020-04-10 10:51:23    371    0    0

 列表元组转其他

# 列表转集合(去重)
list1 = [6, 7, 7, 8, 8, 9]
set(list1)
# {6, 7, 8, 9}
 
#两个列表转字典
list1 = ['key1','key2','key3']
list2 = ['1','2','3']
dict(zip(list1,list2))
# {'key1': '1', 'key2': '2', 'key3': '3'}
 
#嵌套列表转字典
list3 = [['key1','value1'],['key2','value2'],['key3','value3']]
dict(list3)
# {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
 
# 列表、元组转字符串
list2 = ['a', 'a', 'b']
''.join(list2)
# 'aab'
 
tup1 = ('a', 'a', 'b')
''.join(tup1)
# 'aab'

字典转其他

# 字典转换为字符串
dic1 = {'a':1,'b':2}
str(dic1)
# "{'a': 1, 'b': 2}"
 
# 字典key和value互转
dic2 = {'a': 1, 'b': 2, 'c': 3}
{value:key for key, value in a_dict.items()}
# {1: 'a', 2: 'b', 3: 'c'}

字符串转其他

# 字符串转列表
s = 'aabbcc'
list(s)
# ['a', 'a', 'b', 'b', 'c', 'c']
 
# 字符串转元组
tuple(s)
# ('a', 'a', 'b', 'b', 'c', 'c')
 
# 字符串转集合
set(s)
# {'a', 'b', 'c'}
 
# 字符串转字典
dic2 = eval("{'name':'ljq', 'age':24}")
 
# 切分字符串
a = 'a b c'
a.split(' ')
# ['a', 'b', 'c']

JSON和字典之间相互转化

1.首先引入json模块

# 引入json模块
import json

2.转换

#JSON到字典转化:
dictinfo = json.loads(json_str) # 
python    2020-04-10 10:50:56    95    0    0

错误提示:

  1. # pip3 install jupyter
  2. Traceback (most recent call last):
  3. File "/usr/bin/pip3", line 9, in <module>
  4. from pip import main
  5. ImportError: cannot import name 'main'

解决方法:

by clear hash in bash:

  1. $ hash -d pip

Or in dash (sh):

  1. $ hash -r pip
2020-04-10 10:50:56    234    0    0

查看系统python版本

python
Python 2.7.9 (default, Mar  1 2015, 18:22:53)
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>

1.更新软件包

apt-get update
apt-get u