Note


  • Home

  • Archives

python的函数传递

Posted on 2018-01-02
1
2
3
4
5
a = 1
def fun(a):
a = 2
fun(a)
print(a) #1
1
2
3
4
5
a = []
def fun(a):
a.append(1)
fun(a)
print(a) #[1]

在python中,strings, tuples, 和numbers是不可更改的对象,而 list, dict, set 等则是可以修改的对象

python *args 和 **kwargs

Posted on 2017-05-05

*args和**kwargs经常在python的函数中看到,这两个变量并不一定要写成*args **kwargs,也可以写成其他的*var``**vars,规定中只有*和**是必须的。而写成*args和**kwargs是一种通俗的命名规定。

*args和**kwaargs作用

*args和**kwaargs只要用于函数定义。可以用这两个参数把不定数量的参数传给一个函数。

有时候并不知道要传多少参数给函数,这时候就可以使用这两个关键字。

*args的用法

*args用于发送一个非键值对的可变数量的参数列表给一个函数

1
2
3
4
5
6
def test_args(arg, *args):
print("normal arg:", arg)
for arg in args:
print("*arg:", arg)

test_args('normal', 'a', 'b', 'c')

输出:

1
2
3
4
normal arg: normal
*arg: a
*arg: b
*arg: c

**kwargs的用法

**kwargs用于把不定长度的键值对参数发送给函数。例子如下:

1
2
3
4
5
def test_kwargs(**kwargs):
for key,value in kwargs.items():
print("{0} == {1}".format(key,value))

test_kwargs(name="Dlala")

结果如下:

1
name == Dlala

Privoxy 中转代理

Posted on 2017-05-02

最近玩仁王,联机是个很大的问题,需要翻墙,于是买了个shadowsocks再加Privoxy实现代理

shadowscks没啥好说的了,买完装客户端,账户密码一填完事

接下来说说privoxy

安装 privoxy

1
brew install privoxy

配置 privoxy

1
vim /usr/local/etc/privoxy/config

找到listen-address,修改添加

1
2
listen-address  0.0.0.0:8118
forward-socks5 / 127.0.0.1:1080 .

1080是shadowsocks代理的端口,8118是开启http代理的端口。0.0.0.0是为了让代理可以在局域网内使用,如果只想在本地使用,则用127.0.0.1

当然这里为了使ps4能够使用此代理,应该使用0.0.0.0

启动 privoxy

1
/usr/local/sbin/privoxy /usr/local/etc/privoxy/config

检查是否成功启动privoxy

1
netstat -an | grep 8118

看到以下输出时就已经成功开启代理了:

1
tcp4       0      0  *.8118              *.*             LISTEN

Move Zeroes

Posted on 2017-03-01

描述

给定一个数组nums,编写函数将数组内所有0元素移至数组末尾,并保持非0元素相对顺序不变。

例如,给定nums = [0, 1, 0, 3, 12],调用函数完毕后, nums应该是 [1, 3, 12, 0, 0]。

注意:

  1. 你应该“就地”完成此操作,不要复制数组。
  2. 最小化操作总数。

思路

按O(n)的思路来想,应该在遍历一次的过程中完成操作,那么应该有两个“指针”,一个num指针来遍历数组,一个pos来将为0的数字往后移位,遍历完毕后,即完成操作。

代码

1
2
3
4
5
6
7
8
9
10
11
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
pos = 0
for num in range(len(nums)):
if nums[num]:
nums[pos], nums[num] = nums[num], nums[pos]
pos += 1

Minimum Moves to Equal Array Elements

Posted on 2017-03-01

描述

给定一个长度为n的非空整数数组,计算最少需要多少次移动可以使所有元素相等,一次移动是指将n - 1个元素加1。例如:
[1,2,3] => [2,3,3] => [3,4,3] => [4,4,4]

思路

每次使n-1个数字 +1 ,其实就是让最大的数字 -1 的操作,这样来看,就可以得出移动次数为 每个数字减去最小数字的总和,即
count = sun(nums) - min(nums) * len(nums)

代码:

1
2
3
4
5
6
7
class Solution(object):
def minMoves(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return sum(nums) - min(nums) * len(nums)

使用python发送电子邮件

Posted on 2016-12-07
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2016/12/7 上午9:40
# @Author : Dwk
# @File : send_email.py
# smtplib 负责邮件的发送
# email负责邮件的内容
import smtplib
from email.mime.text import MIMEText

# 邮件服务器配置
mail_host = "smtp.gmail.com"
mail_user = "XXX"
mail_pass = "XXXXXX"
sender = "XXXXXXX"
# 可接受多个发送地址
receivers = ["XXXXXX"]

# 邮件内容
# text/html是指以html网页形式发送的,而text/plain是以纯文本格式发送的
message = MIMEText('content', 'plant', 'utf-8')
# 邮件主题
message['Subject'] = 'title'
# 发送方
message['From'] = sender
# 接受方
message['To'] = receivers[0]

# 登录并发送
try:
smtpObj = smtplib.SMTP()
smtpObj.connect(mail_host, 25)
smtpObj = smtplib.SMTP_SSL(mail_host, 465)
smtpObj.login(mail_user, mail_pass)
smtpObj.sendmail(sender, receivers, message.as_string())
smtpObj.quit()
print('success')
except smtplib.SMTPException as e:
print('error', e)

下面这个例子是添加了附件的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2016/12/7 上午9:40
# @Author : Dwk
# @File : send_email.py
# smtplib 负责邮件的发送
# email负责邮件的内容
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage


# 邮件服务器配置
mail_host = "smtp.gmail.com"
mail_user = "dwk715"
mail_pass = "XXXXX"
sender = "dwk715@gmail.com"
# 可接受多个发送地址
receivers = ["dwk715@hotmail.com"]

# 邮件内容
# text/html是指以html网页形式发送的,而text/plain是以纯文本格式发送的
# 邮件主题
message = MIMEMultipart()
message['Subject'] = '测试'
# 发送方
message['From'] = sender
# 接受方
message['To'] = receivers[0]
# 使用HTML的正文内容
with open('content.html', 'r') as f:
content = f.read()
part1 = MIMEText(content, 'html', 'utf-8')
# 添加附件
with open('addone.txt', 'r') as add:
content2 = add.read()
part2 = MIMEText(content2, 'plain', 'utf-8')
# 设置内容类型,为二进制流
part2['Content-Type'] = 'application/octet-stream'
# 设置附件,添加文件名
part2['Content-Disposition'] = 'attachment;filename="addone.txt"'
# 添加照片附件,注意此处是rb读取方式
with open('01.jpg', 'rb') as f_image:
image = MIMEImage(f_image.read())
# 设置内容类型,为二进制流
image['Content-Type'] = 'application/octet-stream'
# 设置附件,添加文件名
image['Content-Disposition'] = 'attachment;filename="01.jpg"'
# 添加内容到邮件主体中
message.attach(part1)
message.attach(part2)
message.attach(image)


# 登录并发送
try:
smtpObj = smtplib.SMTP()
smtpObj.connect(mail_host, 25)
smtpObj = smtplib.SMTP_SSL(mail_host, 465)
smtpObj.login(mail_user, mail_pass)
smtpObj.sendmail(sender, receivers, message.as_string())
smtpObj.quit()
print('success')
except smtplib.SMTPException as e:
print('error', e)

Flask路由

Posted on 2016-11-23
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2016/11/22 下午3:51
# @Author : Dwk
# @File : flask_route.py

from flask import Flask

# 创建一个Flask类的实例
app = Flask(__name__)


# 使用 route() 装饰器告诉 Flask 什么样 的URL 能触发我们的函数

@app.route('/')
def index():
return 'Index Page'


@app.route('/hello')
def hello():
return 'Hello, World'

# 要给 URL 添加变量部分,你可以把这些特殊的字段标记为 <variable_name>。
# 这个部分将会作为命名参数传递到你的函数。
# 规则可以用 <converter:variable_name> 指定一个可选的转换器。

@app.route('/user/<username>')
def show_user_profile(username):
return 'User %s' % username


@app.route('/post/<int:post_id>')
def show_post(post_id):
return 'Post %d' % post_id

# 虽然它们看起来着实相似,但它们结尾斜线的使用在 URL 定义 中不同。
# 第一种情况中,指向projects的规范URL尾端有一个斜线。
# 这种感觉 很像在文件系统中的文件夹。
# 访问一个结尾不带斜线的 URL 会被 Flask 重定向到带斜线的规范 URL 去。

# 然而,第二种情况的 URL 结尾不带斜线,类似 UNIX-like 系统下的文件的 路径名。
# 访问结尾带斜线的 URL 会产生一个 404 “Not Found” 错误。

# 这个行为使得在遗忘尾斜线时,允许关联的 URL 接任工作,与 Apache 和其它的服务器的行为并无二异。
# 此外,也保证了 URL 的唯一,有助于 避免搜索引擎索引同一个页面两次。

@app.route('/projects/')
def projects():
return 'The project page'


@app.route('/about')
def about():
return 'The about page'

virtualenv

Posted on 2016-11-22

python虚环境能够隔离不同版本的python和python库,使各个项目环境保持独立。

  • 安装:
1
pip install virtualenv
  • 部署:
1
2
3
mkdir myproject
cd myproject
virtualenv venv
  • Python的版本指定
1
virtualenv venv --python=python2.7
  • 激活:
1
. venv/bin/activate
  • 回到真实的世界:
1
deactivate

pip国内源

Posted on 2016-11-22

国内的开源python源:

  • 阿里云 http://mirrors.aliyun.com/pypi/simple/
  • 中国科技大学 https://pypi.mirrors.ustc.edu.cn/simple/
  • 豆瓣(douban) http://pypi.douban.com/simple/
  • 清华大学 https://pypi.tuna.tsinghua.edu.cn/simple/
  • 中国科学技术大学 http://pypi.mirrors.ustc.edu.cn/simple/

使用方法为:

pip install 模块名称 -i url

在使用不是https协议的源时,需要加上–trusted-host

收集整个网站数据

Posted on 2016-10-31

收集整个网站的数据

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2016/11/15 下午3:06
# @Author : Dwk
# @File : wikiLink.py

from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
import pymysql.cursors

# 请求URL并把结果使用UTF-8编码
resp = urlopen("https://en.wikipedia.org/wiki/Main_Page").read().decode("utf-8")

# 使用BeautifulSoup解析
soup = BeautifulSoup(resp, "html.parser")

# 获取所有以/wiki/开头的a标签
urls = soup.find_all("a", href=re.compile("^/wiki/"))

# 输出词条对应的名称和URL
for url in urls:
# 过滤以.jpg或者.JPG结尾的链接
if not re.search("\.(jpg|JPG)$", url["href"]):
# 输出url的文字和对应的链接
print('{0:40} --> {1:10}'.format(url.get_text(), "https://en.wikipedia.org/wiki/" + url["href"]))
# 获取数据库链接
connection = pymysql.connect(host='localhost',
user='root',
password='0715',
db='wikiUrls',
charset='utf8mb4')

try:
# 获取会话指针
with connection.cursor() as cursor:
# 创建sql语句
sql = "insert into `urls`(`urlName`, `urlHref`) values (%s, %s)"
# 执行sql语句
cursor.execute(sql, (url.get_text(), "https://en.wikipedia.org/wiki/" + url["href"]))
# 提交
connection.commit()
finally:
connection.close()

下面是操作已保存的数据库的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2016/11/15 下午4:35
# @Author : Dwk
# @File : readMysql.py

import pymysql.cursors

# 获取链接
connection = pymysql.connect(host='localhost',
user='root',
password='0715',
db='wikiUrls',
charset='utf8mb4')
try:
# 获取会话指针
with connection.cursor() as cursor:
# 查询语句数量
sql = "select `urlName`,`urlHref` FROM `urls` where `id` is not null"
count = cursor.execute(sql)
print(count)
# 查询数据
result = cursor.fetchmany(size=3)
print(result)
result = cursor.fetchall()
print(result)
finally:
connection.close()
123

Dlala

编程是不可能离开Google的( ̄^ ̄)ゞ

26 posts
18 tags
© 2018 Dlala
Powered by Hexo
|
Theme — NexT.Muse v5.1.4