pycharm debug scrapy 报错 twisted.internet.error.ReactorNotRestartable

python爬虫李魔佛 发表了文章 • 0 个评论 • 7056 次浏览 • 2019-04-23 11:35 • 来自相关话题

没发现哪里不妥,以前debug调试scrapy一直没问题。 
后来才发现,
scrapy run的启动文件名不能命令为cmd.py !!!!!
我把scrapy的启动写到cmd.py里面
from scrapy import cmdline cmdline.execute('scrapy crawl xxxx'.split())
 
然后cmd.py和系统某个调试功能的库重名了。 查看全部
没发现哪里不妥,以前debug调试scrapy一直没问题。 
后来才发现,
scrapy run的启动文件名不能命令为cmd.py !!!!!
我把scrapy的启动写到cmd.py里面
from scrapy import cmdline cmdline.execute('scrapy crawl xxxx'.split())
 
然后cmd.py和系统某个调试功能的库重名了。

python不支持多重继承中的重复继承

李魔佛 发表了文章 • 0 个评论 • 3358 次浏览 • 2019-04-18 16:36 • 来自相关话题

代码如下:
class First(object):
def __init__(self):
print("first")

class Second(First):
def __init__(self):
print("second")

class Third(First,Second):
def __init__(self):
print("third")
运行代码会直接报错:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-6-c90f7b77d3e0> in <module>()
7 print("second")
8
----> 9 class Third(First,Second):
10 def __init__(self):
11 print("third")

TypeError: Cannot create a consistent method resolution order (MRO) for bases First, Second
  查看全部
代码如下:
class First(object):
def __init__(self):
print("first")

class Second(First):
def __init__(self):
print("second")

class Third(First,Second):
def __init__(self):
print("third")

运行代码会直接报错:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-6-c90f7b77d3e0> in <module>()
7 print("second")
8
----> 9 class Third(First,Second):
10 def __init__(self):
11 print("third")

TypeError: Cannot create a consistent method resolution order (MRO) for bases First, Second

 

gevent异步 入门教程(入坑)

李魔佛 发表了文章 • 0 个评论 • 3979 次浏览 • 2019-04-18 11:37 • 来自相关话题

code1
import time
import gevent
import requests
def foo():
print('Running in foo')

r=requests.get('http://30daydo.com')
print(r.status_code)
print('Explicit context switch to foo again')

def bar():
print('Explicit context to bar')

r=requests.get('http://www.qq.com') #
print(r.status_code)
print('Implicit context switch back to bar')

start=time.time()
gevent.joinall([
gevent.spawn(foo),
gevent.spawn(bar),
])
print('time used {}'.format(time.time()-start))
上面的异步代码不起作用,因为requests阻塞了,所以用的时间和顺序执行的时间一样.
 
或者用以下代码替代:
import time
import gevent
import requests
def foo():
print('Running in foo')
time.sleep(2) # 这样子不起作用
print('Explicit context switch to foo again')

def bar():
print('Explicit context to bar')
time.sleep(2)
print('Implicit context switch back to bar')

start=time.time()
gevent.joinall([
gevent.spawn(foo),
gevent.spawn(bar),
])
print('time used {}'.format(time.time()-start))
把访问网络部分使用sleep替代,那么最后的运行时间是2+2 =4秒,并不是2秒,那么要怎样才是2秒呢,需要改成以下的代码:
 
import time
import gevent
import requests
def foo():
print('Running in foo')

gevent.sleep(2) # 通过它各自yield向对方

print('Explicit context switch to foo again')

def bar():
print('Explicit context to bar')

gevent.sleep(2)

print('Implicit context switch back to bar')

start=time.time()
gevent.joinall([
gevent.spawn(foo),
gevent.spawn(bar),
])
print('time used {}'.format(time.time()-start))
使用gevent.sleep()
这个函数才可以达到目的. 查看全部
code1
import time
import gevent
import requests
def foo():
print('Running in foo')

r=requests.get('http://30daydo.com')
print(r.status_code)
print('Explicit context switch to foo again')

def bar():
print('Explicit context to bar')

r=requests.get('http://www.qq.com') #
print(r.status_code)
print('Implicit context switch back to bar')

start=time.time()
gevent.joinall([
gevent.spawn(foo),
gevent.spawn(bar),
])
print('time used {}'.format(time.time()-start))

上面的异步代码不起作用,因为requests阻塞了,所以用的时间和顺序执行的时间一样.
 
或者用以下代码替代:
import time
import gevent
import requests
def foo():
print('Running in foo')
time.sleep(2) # 这样子不起作用
print('Explicit context switch to foo again')

def bar():
print('Explicit context to bar')
time.sleep(2)
print('Implicit context switch back to bar')

start=time.time()
gevent.joinall([
gevent.spawn(foo),
gevent.spawn(bar),
])
print('time used {}'.format(time.time()-start))

把访问网络部分使用sleep替代,那么最后的运行时间是2+2 =4秒,并不是2秒,那么要怎样才是2秒呢,需要改成以下的代码:
 
import time
import gevent
import requests
def foo():
print('Running in foo')

gevent.sleep(2) # 通过它各自yield向对方

print('Explicit context switch to foo again')

def bar():
print('Explicit context to bar')

gevent.sleep(2)

print('Implicit context switch back to bar')

start=time.time()
gevent.joinall([
gevent.spawn(foo),
gevent.spawn(bar),
])
print('time used {}'.format(time.time()-start))

使用gevent.sleep()
这个函数才可以达到目的.

python的pip安装mysqldb

李魔佛 发表了文章 • 0 个评论 • 3349 次浏览 • 2019-04-16 23:51 • 来自相关话题

换一个新环境,或者在另一台服务器上运行自己的程序,最烦就是pip安装各种依赖,尤其其他机器上的python不一致(你用的是python3,服务器用的是python2),或者两个系统都不一致。 这个时候pip安装第三方库就很折腾。
 
比如mysqldb这个库,windows用python2不知道怎样才能装上。 反正这个我几年装过,现在已经忘记怎么安装了。
今天又要装一遍,为了减轻痛苦,安装anaconda,然后使用conda install mysqldb,conda会帮你把依赖都解决掉。 不然你要装一堆的VC8,VC14, 等等。
 
然后等待一下,就安装好了。 查看全部
换一个新环境,或者在另一台服务器上运行自己的程序,最烦就是pip安装各种依赖,尤其其他机器上的python不一致(你用的是python3,服务器用的是python2),或者两个系统都不一致。 这个时候pip安装第三方库就很折腾。
 
比如mysqldb这个库,windows用python2不知道怎样才能装上。 反正这个我几年装过,现在已经忘记怎么安装了。
今天又要装一遍,为了减轻痛苦,安装anaconda,然后使用conda install mysqldb,conda会帮你把依赖都解决掉。 不然你要装一堆的VC8,VC14, 等等。
 
然后等待一下,就安装好了。

最流行的版本控制软件:git 个人笔记

李魔佛 发表了文章 • 0 个评论 • 4058 次浏览 • 2019-04-16 23:37 • 来自相关话题

最流行的版本控制软件:git
========================

git已经是当前最流行的版本控制软件之一了。全世界的程序员都在使用它。它出自linus大神之手,现在被用于内
核的版本控制。在最流行的代码托管软件github,你几乎可以找到所有开源项目的代码。

版块控制软件:我需要吗?
-----------------------

的确对于许多人——尤其是非程序员,他们可能不会想到已经出现了专门的版本控制的软件。但其实多人对版本控
制其实都有类似的需求,举个例子,Tom是社团的秘书处成员,他们经常需要做的事情就是写活动文档,然后不停地
改改到大家都觉得可以了。

不幸运的话,Tom可能有个文件夹叫“openSUSE活动策划",里面有这样的一堆文件”openSUSE活动策划", "活动策
划1", "活动策划2", "活动策划3", "活动策划4" ... "活动策划20" (可怜的Tom,一份文档改了不少于20次)

这种作法很有效,因为我们可能发现第5个版本的策划有问题,我们准备在第3个版本上面重新来过。但是也看到,
这个作法有些很丑陋的地方:一份文件,我们留了20个备份,而且还要注意文件名。

如果可以这样就好了:文件夹上只有一个“openSUSE活动策划",但当我需要第5个版本的时候,我来一个”给我还
原到第5个版本吧!“,然后这时候我们打开这个文件,它就是第5个版本的了。类似的,我们可以取出任意的版本


这就是版本控制。这种事情在程序里面发生的太多了,于是出现了各种版本控制软件。事实上,有些项目已经发展
到第1000+甚至更高的版本数了……

单线的工作流
------------

我们可以把我们的一个项目想象为一个仓库,然后我们可以把我们的东西塞进仓库里面,也可以把想要的东西拿出
来。而git则是仓库的管理员。下面是一个例子,希望有一个直观的印象,不求完全的理解和掌握。

```bash
mkdir myproject // 假设myproject是工作目录
cd myproject
git init // git <- (init) ,告诉仓库管理员,在当前目录初始化
echo 'Eat the banana' > file // 编辑了一个文件
git add file // 加入仓库
git commit -m 'add first file' // 提交更改
echo 'Eat the apply' > file // 修改了这个文件
git add file // 加入仓库
git commit -m 'update first file' // 再提交更改
```

这时候我们就有两个commit了,我们来看看工作日志:

```bash
git log

# 以下是输出
# commit ac1371173b4e630ddaebda3f9f5d948b36146c07
# Author: Norman Mo <LTaoist@@@>
# Date: Thu Jun 27 21:59:10 2013 +0800
#
# update first file
#
# commit 3c43cc913454f92bb4b80c56ba45e4ffaf556fc0
# Author: Norman Mo <LTaoist6@@@@>
# Date: Thu Jun 27 21:58:48 2013 +0800
#
# add first file
```

看到了,我们提交了两次。我们来看看现在file里面是什么:

```bash
cat file # 显然输出是 'Eat the apply'
# 现在,我们来拿回第一个版本的file文件
git checkout 3c43cc913454f92bb4b80c56ba45e4ffaf556fc0 -- file
cat file # 这时候就是eat banana了
```

这种工作的方式是单人使用最常见的方式,写一点代码,提交一下到仓库里面。写一点,提交到仓库里面。然后出
问题的时候就回退过去。git非常强大,基本上你想到的他都可以做到,提交到仓库的数据基本不会丢失,像时间机
器一样控制着代码。

多人协作
--------

git非常强大,上面只是一个功能。考虑Tom的秘书处有两个人,他们在同时写。其中Tom写前6章,他的同伴写第7~
12章。

这时候可以考虑用这种工作的方式:设立一个公共的仓库。Tom维护自己的版本,他的同伴维护自己的版本。然后大
家定期把代码合并到公共仓库上面,然后定期把新的版本取回来合并再提交到公共仓库。

如果他们用纯文本,得益于一些文本分析的方法,几乎不需要校对就可以做到。

```
git commit -m 'finish ch5' // 假设此时Tom写完了第5章
git push // Tom将代码推送到远程仓库
```

```
git commit -m 'finish ch11' // 假设此时Tom的同伴完成了第11章
git pull // pull会将最新版本拉下来,合并,然后推送到远程仓库
```

实际上工作中,为了不混淆,会新开一个分支来开发新的特性,然后对分支进行合并。

代码自动发布
-----------

另一个很强大的功能是可以实现代码的自动发布。事实上,很多云就有使用这个。具体来说,利用git的hooks,当
服务器收到一个push,服务器可以自动运行一些脚本。也可以在客户端使用hooks,当客户端准备push的时候,客户
端先运行一些脚本。

例如,我们希望在每次服务器收到push以后,杀死全部的 `p` 进程,然后重开 `p` 进程。我们可以修改 `hooks/
post-receive` :

```
echo "Killing all p process..."
killall -9 p
echo "Restart p process..."
p
```

更多更多更多……
---------------

这份教程就到这里了,更多的自己马上动手去试试吧!

在openSUSE的安装方法:

```
sudo zypper in git
```

默认应该就装了。

一般linux命令查看帮助都是 `--help` 选项:

```
git --help
```

此外,对一个子命令也是有help看的:

```
git init --help
```

这里有一个交互教程,在浏览器上面跑的模拟git的运行的,有兴趣的试试:

<http://try.github.io/>

github的help文档写得很不错,推荐一下:

<https://help.github.com/>

书籍有个远近闻名的《Pro Git》,而且有中文版的,虽然我认为这本书太厚了。。。但似乎就这么一本书……

<http://git-scm.com/book/zh>

国内有个gitcafe,也是做git托管的,他们也有整理一份help:

<https://gitcafe.com/GitCafe/Help>

记得,上面只是一个演示,多试试push,多尝试。有一天你会喜欢用这个有效的工具的。

很有用!!! 查看全部

最流行的版本控制软件:git
========================

git已经是当前最流行的版本控制软件之一了。全世界的程序员都在使用它。它出自linus大神之手,现在被用于内
核的版本控制。在最流行的代码托管软件github,你几乎可以找到所有开源项目的代码。

版块控制软件:我需要吗?
-----------------------

的确对于许多人——尤其是非程序员,他们可能不会想到已经出现了专门的版本控制的软件。但其实多人对版本控
制其实都有类似的需求,举个例子,Tom是社团的秘书处成员,他们经常需要做的事情就是写活动文档,然后不停地
改改到大家都觉得可以了。

不幸运的话,Tom可能有个文件夹叫“openSUSE活动策划",里面有这样的一堆文件”openSUSE活动策划", "活动策
划1", "活动策划2", "活动策划3", "活动策划4" ... "活动策划20" (可怜的Tom,一份文档改了不少于20次)

这种作法很有效,因为我们可能发现第5个版本的策划有问题,我们准备在第3个版本上面重新来过。但是也看到,
这个作法有些很丑陋的地方:一份文件,我们留了20个备份,而且还要注意文件名。

如果可以这样就好了:文件夹上只有一个“openSUSE活动策划",但当我需要第5个版本的时候,我来一个”给我还
原到第5个版本吧!“,然后这时候我们打开这个文件,它就是第5个版本的了。类似的,我们可以取出任意的版本


这就是版本控制。这种事情在程序里面发生的太多了,于是出现了各种版本控制软件。事实上,有些项目已经发展
到第1000+甚至更高的版本数了……

单线的工作流
------------

我们可以把我们的一个项目想象为一个仓库,然后我们可以把我们的东西塞进仓库里面,也可以把想要的东西拿出
来。而git则是仓库的管理员。下面是一个例子,希望有一个直观的印象,不求完全的理解和掌握。

```bash
mkdir myproject // 假设myproject是工作目录
cd myproject
git init // git <- (init) ,告诉仓库管理员,在当前目录初始化
echo 'Eat the banana' > file // 编辑了一个文件
git add file // 加入仓库
git commit -m 'add first file' // 提交更改
echo 'Eat the apply' > file // 修改了这个文件
git add file // 加入仓库
git commit -m 'update first file' // 再提交更改
```

这时候我们就有两个commit了,我们来看看工作日志:

```bash
git log

# 以下是输出
# commit ac1371173b4e630ddaebda3f9f5d948b36146c07
# Author: Norman Mo <LTaoist@@@>
# Date: Thu Jun 27 21:59:10 2013 +0800
#
# update first file
#
# commit 3c43cc913454f92bb4b80c56ba45e4ffaf556fc0
# Author: Norman Mo <LTaoist6@@@@>
# Date: Thu Jun 27 21:58:48 2013 +0800
#
# add first file
```

看到了,我们提交了两次。我们来看看现在file里面是什么:

```bash
cat file # 显然输出是 'Eat the apply'
# 现在,我们来拿回第一个版本的file文件
git checkout 3c43cc913454f92bb4b80c56ba45e4ffaf556fc0 -- file
cat file # 这时候就是eat banana了
```

这种工作的方式是单人使用最常见的方式,写一点代码,提交一下到仓库里面。写一点,提交到仓库里面。然后出
问题的时候就回退过去。git非常强大,基本上你想到的他都可以做到,提交到仓库的数据基本不会丢失,像时间机
器一样控制着代码。

多人协作
--------

git非常强大,上面只是一个功能。考虑Tom的秘书处有两个人,他们在同时写。其中Tom写前6章,他的同伴写第7~
12章。

这时候可以考虑用这种工作的方式:设立一个公共的仓库。Tom维护自己的版本,他的同伴维护自己的版本。然后大
家定期把代码合并到公共仓库上面,然后定期把新的版本取回来合并再提交到公共仓库。

如果他们用纯文本,得益于一些文本分析的方法,几乎不需要校对就可以做到。

```
git commit -m 'finish ch5' // 假设此时Tom写完了第5章
git push // Tom将代码推送到远程仓库
```

```
git commit -m 'finish ch11' // 假设此时Tom的同伴完成了第11章
git pull // pull会将最新版本拉下来,合并,然后推送到远程仓库
```

实际上工作中,为了不混淆,会新开一个分支来开发新的特性,然后对分支进行合并。

代码自动发布
-----------

另一个很强大的功能是可以实现代码的自动发布。事实上,很多云就有使用这个。具体来说,利用git的hooks,当
服务器收到一个push,服务器可以自动运行一些脚本。也可以在客户端使用hooks,当客户端准备push的时候,客户
端先运行一些脚本。

例如,我们希望在每次服务器收到push以后,杀死全部的 `p` 进程,然后重开 `p` 进程。我们可以修改 `hooks/
post-receive` :

```
echo "Killing all p process..."
killall -9 p
echo "Restart p process..."
p
```

更多更多更多……
---------------

这份教程就到这里了,更多的自己马上动手去试试吧!

在openSUSE的安装方法:

```
sudo zypper in git
```

默认应该就装了。

一般linux命令查看帮助都是 `--help` 选项:

```
git --help
```

此外,对一个子命令也是有help看的:

```
git init --help
```

这里有一个交互教程,在浏览器上面跑的模拟git的运行的,有兴趣的试试:

<http://try.github.io/>

github的help文档写得很不错,推荐一下:

<https://help.github.com/>

书籍有个远近闻名的《Pro Git》,而且有中文版的,虽然我认为这本书太厚了。。。但似乎就这么一本书……

<http://git-scm.com/book/zh>

国内有个gitcafe,也是做git托管的,他们也有整理一份help:

<https://gitcafe.com/GitCafe/Help>

记得,上面只是一个演示,多试试push,多尝试。有一天你会喜欢用这个有效的工具的。

很有用!!!

CentOS Zookeeper无法启动:Error contacting service,It is probably not running

python爬虫李魔佛 发表了文章 • 0 个评论 • 5469 次浏览 • 2019-04-09 19:20 • 来自相关话题

启动:
./kafka-server-start.sh -daemon ../config/server.properties
报错:
Error contacting service,It is probably not running
 
关闭重启,杀进程,看端口是否被占用。无果。
后来看了下防火墙,OMG,有一台机子的防火墙没有关闭。
 
手工关闭后问题就解决了。
 
关闭防火墙命令:
systemctl stop firewalld.service #关闭防火墙
systemctl disable firewalld.service #禁止启动防火墙 查看全部
启动:
./kafka-server-start.sh -daemon ../config/server.properties
报错:
Error contacting service,It is probably not running
 
关闭重启,杀进程,看端口是否被占用。无果。
后来看了下防火墙,OMG,有一台机子的防火墙没有关闭。
 
手工关闭后问题就解决了。
 
关闭防火墙命令:
systemctl stop firewalld.service #关闭防火墙
systemctl disable firewalld.service #禁止启动防火墙

numpy datetime转为date,pandas的日期类型转为python的daetime

李魔佛 发表了文章 • 0 个评论 • 8729 次浏览 • 2019-04-08 15:40 • 来自相关话题

dataframe的数据格式是这样子的:





 
info看一下里面的数据类型:<class 'pandas.core.frame.DataFrame'>
RangeIndex: 307 entries, 0 to 306
Data columns (total 7 columns):
日期 307 non-null datetime64[ns]
指数 307 non-null float64
成交额(亿元) 307 non-null float64
涨跌 307 non-null float64
涨跌额 307 non-null float64
转债数目 307 non-null float64
剩余规模 307 non-null float64
dtypes: datetime64[ns](1), float64(6)
memory usage: 16.9 KB
日期 307 non-null datetime64[ns]
 
然后转为list看看:
a=list(df['日期'].values)
如果使用上面的方法,返回的是这样的数据:[numpy.datetime64('2017-12-29T00:00:00.000000000'),
numpy.datetime64('2018-01-02T00:00:00.000000000'),
numpy.datetime64('2018-01-03T00:00:00.000000000'),
numpy.datetime64('2018-01-04T00:00:00.000000000'),
numpy.datetime64('2018-01-05T00:00:00.000000000'),
numpy.datetime64('2018-01-08T00:00:00.000000000'),
numpy.datetime64('2018-01-09T00:00:00.000000000'),
numpy.datetime64('2018-01-10T00:00:00.000000000'),
numpy.datetime64('2018-01-11T00:00:00.000000000'),
numpy.datetime64('2018-01-12T00:00:00.000000000'),
numpy.datetime64('2018-01-15T00:00:00.000000000'),
numpy.datetime64('2018-01-16T00:00:00.000000000'),
numpy.datetime64('2018-01-17T00:00:00.000000000'),
 
如何转化为python的daetime格式呢?
 
可以使用内置的:s.dt.to_pydatetime()
s为df的一列,也就是series数据格式b=list(df['日期'].dt.to_pydatetime())得到的是[datetime.datetime(2017, 12, 29, 0, 0),
datetime.datetime(2018, 1, 2, 0, 0),
datetime.datetime(2018, 1, 3, 0, 0),
datetime.datetime(2018, 1, 4, 0, 0),
datetime.datetime(2018, 1, 5, 0, 0),
datetime.datetime(2018, 1, 8, 0, 0),
datetime.datetime(2018, 1, 9, 0, 0),
datetime.datetime(2018, 1, 10, 0, 0),
datetime.datetime(2018, 1, 11, 0, 0),
datetime.datetime(2018, 1, 12, 0, 0),
datetime.datetime(2018, 1, 15, 0, 0)
为了不想要小时,分钟,秒的数据,可以清洗一下:
b=[i.strftime('%Y-%m-%d') for i in b]
 
得到:['2017-12-29',
'2018-01-02',
'2018-01-03',
'2018-01-04',
'2018-01-05',
'2018-01-08',
'2018-01-09',
'2018-01-10',
'2018-01-11',
'2018-01-12',
'2018-01-15',
'2018-01-16',
'2018-01-17',] 
  查看全部
dataframe的数据格式是这样子的:

d1.PNG

 
info看一下里面的数据类型:
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 307 entries, 0 to 306
Data columns (total 7 columns):
日期 307 non-null datetime64[ns]
指数 307 non-null float64
成交额(亿元) 307 non-null float64
涨跌 307 non-null float64
涨跌额 307 non-null float64
转债数目 307 non-null float64
剩余规模 307 non-null float64
dtypes: datetime64[ns](1), float64(6)
memory usage: 16.9 KB

日期 307 non-null datetime64[ns]
 
然后转为list看看:
a=list(df['日期'].values)
如果使用上面的方法,返回的是这样的数据:
[numpy.datetime64('2017-12-29T00:00:00.000000000'),
numpy.datetime64('2018-01-02T00:00:00.000000000'),
numpy.datetime64('2018-01-03T00:00:00.000000000'),
numpy.datetime64('2018-01-04T00:00:00.000000000'),
numpy.datetime64('2018-01-05T00:00:00.000000000'),
numpy.datetime64('2018-01-08T00:00:00.000000000'),
numpy.datetime64('2018-01-09T00:00:00.000000000'),
numpy.datetime64('2018-01-10T00:00:00.000000000'),
numpy.datetime64('2018-01-11T00:00:00.000000000'),
numpy.datetime64('2018-01-12T00:00:00.000000000'),
numpy.datetime64('2018-01-15T00:00:00.000000000'),
numpy.datetime64('2018-01-16T00:00:00.000000000'),
numpy.datetime64('2018-01-17T00:00:00.000000000'),

 
如何转化为python的daetime格式呢?
 
可以使用内置的:s.dt.to_pydatetime()
s为df的一列,也就是series数据格式
b=list(df['日期'].dt.to_pydatetime())
得到的是
[datetime.datetime(2017, 12, 29, 0, 0),
datetime.datetime(2018, 1, 2, 0, 0),
datetime.datetime(2018, 1, 3, 0, 0),
datetime.datetime(2018, 1, 4, 0, 0),
datetime.datetime(2018, 1, 5, 0, 0),
datetime.datetime(2018, 1, 8, 0, 0),
datetime.datetime(2018, 1, 9, 0, 0),
datetime.datetime(2018, 1, 10, 0, 0),
datetime.datetime(2018, 1, 11, 0, 0),
datetime.datetime(2018, 1, 12, 0, 0),
datetime.datetime(2018, 1, 15, 0, 0)

为了不想要小时,分钟,秒的数据,可以清洗一下:
b=[i.strftime('%Y-%m-%d') for i in b]
 
得到:
['2017-12-29',
'2018-01-02',
'2018-01-03',
'2018-01-04',
'2018-01-05',
'2018-01-08',
'2018-01-09',
'2018-01-10',
'2018-01-11',
'2018-01-12',
'2018-01-15',
'2018-01-16',
'2018-01-17',]
 
 

python datetime模块:timestamp转为本地时间(东八区)

李魔佛 发表了文章 • 0 个评论 • 8827 次浏览 • 2019-04-04 15:15 • 来自相关话题

一般timestamp时间戳格式为10位,如果是13位,则需要除以1000,

1554369904000
为例,计算这个数字的本地时间。
 
如果使用
t=1554369904000
datetime.datetime.fromtimestamp(t/1000)
 
得到的是:
(2019, 4, 4, 17, 25, 4)
 
然而这个时间并不是我想要的,和我想要的时间差了8个时区。
 
那么可以使用
datetime.datetime.utcfromtimestamp(t/1000)
这个返回的就是我想要的时间了
(2019, 4, 4, 9, 25, 4)
 
 
引用:
timestamp转换为datetime
要把timestamp转换为datetime,使用datetime提供的fromtimestamp()方法:

>>> from datetime import datetime
>>> t = 1429417200.0
>>> print(datetime.fromtimestamp(t))
2015-04-19 12:20:00
注意到timestamp是一个浮点数,它没有时区的概念,而datetime是有时区的。上述转换是在timestamp和本地时间做转换。

本地时间是指当前操作系统设定的时区。例如北京时区是东8区,则本地时间:

2015-04-19 12:20:00
实际上就是UTC+8:00时区的时间:

2015-04-19 12:20:00 UTC+8:00
而此刻的格林威治标准时间与北京时间差了8小时,也就是UTC+0:00时区的时间应该是:

2015-04-19 04:20:00 UTC+0:00
timestamp也可以直接被转换到UTC标准时区的时间:

>>> from datetime import datetime
>>> t = 1429417200.0
>>> print(datetime.fromtimestamp(t)) # 本地时间
2015-04-19 12:20:00
>>> print(datetime.utcfromtimestamp(t)) # UTC时间
2015-04-19 04:20:00
 
  查看全部
一般timestamp时间戳格式为10位,如果是13位,则需要除以1000,

1554369904000
为例,计算这个数字的本地时间。
 
如果使用
t=1554369904000
datetime.datetime.fromtimestamp(t/1000)
 
得到的是:
(2019, 4, 4, 17, 25, 4)
 
然而这个时间并不是我想要的,和我想要的时间差了8个时区。
 
那么可以使用
datetime.datetime.utcfromtimestamp(t/1000)
这个返回的就是我想要的时间了
(2019, 4, 4, 9, 25, 4)
 
 
引用:
timestamp转换为datetime
要把timestamp转换为datetime,使用datetime提供的fromtimestamp()方法:

>>> from datetime import datetime
>>> t = 1429417200.0
>>> print(datetime.fromtimestamp(t))
2015-04-19 12:20:00
注意到timestamp是一个浮点数,它没有时区的概念,而datetime是有时区的。上述转换是在timestamp和本地时间做转换。

本地时间是指当前操作系统设定的时区。例如北京时区是东8区,则本地时间:

2015-04-19 12:20:00
实际上就是UTC+8:00时区的时间:

2015-04-19 12:20:00 UTC+8:00
而此刻的格林威治标准时间与北京时间差了8小时,也就是UTC+0:00时区的时间应该是:

2015-04-19 04:20:00 UTC+0:00
timestamp也可以直接被转换到UTC标准时区的时间:

>>> from datetime import datetime
>>> t = 1429417200.0
>>> print(datetime.fromtimestamp(t)) # 本地时间
2015-04-19 12:20:00
>>> print(datetime.utcfromtimestamp(t)) # UTC时间
2015-04-19 04:20:00

 
 

【python】pymongo find_one_and_update的用法

python爬虫李魔佛 发表了文章 • 0 个评论 • 15460 次浏览 • 2019-04-04 11:31 • 来自相关话题

原生的mongo语句是这样的:db.collection.findOneAndUpdate(
<filter>,
<update>,
{
projection: <document>,
sort: <document>,
maxTimeMS: <number>,
upsert: <boolean>,
returnNewDocument: <boolean>,
collation: <document>,
arrayFilters: [ <filterdocument1>, ... ]
}
)
转换成python pymongo是这样的:>>> db.example.find_one_and_update(
... {'_id': 'userid'},
... {'$inc': {'seq': 1}},
... projection={'seq': True, '_id': False},
... return_document=ReturnDocument.AFTER)
上面的语句的意思是:
找到_id 为userid的值得文档,然后把该文档中的seq的值+1,然后返回seq的数据,不显示_id列
最后返回的数据是这样的:

{'seq': 2}
 
注意
findOneAndUpdate
是获取mongo文档中第一条满足条件的数据并做修改。该函数是线程安全的。意思就是在多个线程中操作,不会对同一条数据进行获取修改。
也就是该操作是原子操作。
 
ReturnDocument 引用的库
 
class pymongo.collection.ReturnDocument
 
在开头 from pymongo.collection import ReturnDocument
 
原创文章
转载请注明出处:
http://30daydo.com/article/445 查看全部
原生的mongo语句是这样的:
db.collection.findOneAndUpdate(
<filter>,
<update>,
{
projection: <document>,
sort: <document>,
maxTimeMS: <number>,
upsert: <boolean>,
returnNewDocument: <boolean>,
collation: <document>,
arrayFilters: [ <filterdocument1>, ... ]
}
)

转换成python pymongo是这样的:
>>> db.example.find_one_and_update(
... {'_id': 'userid'},
... {'$inc': {'seq': 1}},
... projection={'seq': True, '_id': False},
... return_document=ReturnDocument.AFTER)

上面的语句的意思是:
找到_id 为userid的值得文档,然后把该文档中的seq的值+1,然后返回seq的数据,不显示_id列
最后返回的数据是这样的:

{'seq': 2}
 
注意
findOneAndUpdate
是获取mongo文档中第一条满足条件的数据并做修改。该函数是线程安全的。意思就是在多个线程中操作,不会对同一条数据进行获取修改。
也就是该操作是原子操作。
 
ReturnDocument 引用的库
 
class pymongo.collection.ReturnDocument
 
在开头 from pymongo.collection import ReturnDocument
 
原创文章
转载请注明出处:
http://30daydo.com/article/445

【Dataframe warning】Try using .loc[row_indexer,col_indexer] = value instead

李魔佛 发表了文章 • 0 个评论 • 12152 次浏览 • 2019-04-02 22:48 • 来自相关话题

使用dataframe直接赋值操作时
 
df['当前日期'] = datetime.date.today()
 
会出现下面的警告信息
Try using .loc[row_indexer,col_indexer] = value instead 
 
虽然得到的最终结果是正常的,可是为什么会出现上面的警告呢?
 
因为上面的操作如果稍微复杂点,那么就可能导致赋值失败。 因为中间会产生一个切片的临时副本。
 
比如:
df
A B C D E
0 5 0 3 3 7
1 9 3 5 2 4
2 7 6 8 8 1
如果想把A列中大于5的数换成100,如何操作 ?
 
A B C D E
0 5 0 3 3 7
1 1000 3 5 2 4
2 1000 6 8 8 1

df[df.A > 5]['A'] = 1000
 
上面的这个表达式是不会生效的。
 
要生效,需要写成以下:
df.loc[df.A > 5, 'A'] = 1000
 
为什么呢?
因为df[df.A]得到是一个临时切片结果,等于一个中间变量,然后在这个中间变量上的A列上做赋值操作,但是最原始的df却没有被改变。
或者你可以这样写
df=df[df.A>5]
df.A=1000
 
 
  查看全部
使用dataframe直接赋值操作时
 
df['当前日期'] = datetime.date.today()
 
会出现下面的警告信息
Try using .loc[row_indexer,col_indexer] = value instead 
 
虽然得到的最终结果是正常的,可是为什么会出现上面的警告呢?
 
因为上面的操作如果稍微复杂点,那么就可能导致赋值失败。 因为中间会产生一个切片的临时副本。
 
比如:
df
A B C D E
0 5 0 3 3 7
1 9 3 5 2 4
2 7 6 8 8 1

如果想把A列中大于5的数换成100,如何操作 ?
 
      A  B  C  D  E
0 5 0 3 3 7
1 1000 3 5 2 4
2 1000 6 8 8 1


df[df.A > 5]['A'] = 1000
 
上面的这个表达式是不会生效的。
 
要生效,需要写成以下:
df.loc[df.A > 5, 'A'] = 1000
 
为什么呢?
因为df[df.A]得到是一个临时切片结果,等于一个中间变量,然后在这个中间变量上的A列上做赋值操作,但是最原始的df却没有被改变。
或者你可以这样写
df=df[df.A>5]
df.A=1000
 
 
 

python析构函数的执行顺序

李魔佛 发表了文章 • 0 个评论 • 3888 次浏览 • 2019-04-01 21:28 • 来自相关话题

在python里面,由于有自动回收内存的机制,所以析构函数的用处要比C++弱得多。 
 
下面看代码:
 
class Foobar(object):

def __init__(self):
print('class start')

def __del__(self):
print('class end')

def main()
obj = Foobar()
print('where is del?')
print('main end')

main()
上面的代码输出结果是什么呢? 卖个关子,自己执行看看吧。 查看全部
在python里面,由于有自动回收内存的机制,所以析构函数的用处要比C++弱得多。 
 
下面看代码:
 
class Foobar(object):

def __init__(self):
print('class start')

def __del__(self):
print('class end')

def main()
obj = Foobar()
print('where is del?')
print('main end')

main()

上面的代码输出结果是什么呢? 卖个关子,自己执行看看吧。

pycharm中格式化json字符

李魔佛 发表了文章 • 0 个评论 • 28415 次浏览 • 2019-03-29 09:25 • 来自相关话题

首先把json字符保存为json后缀,然后看看json字符串中是否用的双引号,注意,单引号不起作用,要把单引号替换成双引号,然后按快捷键ctrl+alt+L 就可以快速格式化json了。
 
效果如下
 





 
首先把json字符保存为json后缀,然后看看json字符串中是否用的双引号,注意,单引号不起作用,要把单引号替换成双引号,然后按快捷键ctrl+alt+L 就可以快速格式化json了。
 
效果如下
 

json.PNG

 

scrapy命令行执行传递多个参数给spider 动态传参

python爬虫李魔佛 发表了文章 • 0 个评论 • 8444 次浏览 • 2019-03-28 11:24 • 来自相关话题

有时候在命令行执行scrapy,比如scrapy crawl spiderXXXX,如果我想要传递一个自定义的参数进去给scrapy,比如我想传递一个爬取的页码数目,我要每次爬取10页。
 
那么需要在spider中定义一个构造函数
  def __init__(self,page=None,*args, **kwargs):
super(Gaode,self).__init__(*args, **kwargs)
self.page=page


def start_requests(self):
XXXXXX 调用self.page 即可
yield Request(XXXX)
 
然后在启动scrapy的时候赋予参数的值:
 
scrapy crawl spider -a page=10
 
就可以动态传入参数
 
原创文章
转载请注明出处:http://30daydo.com/article/436
  查看全部
有时候在命令行执行scrapy,比如scrapy crawl spiderXXXX,如果我想要传递一个自定义的参数进去给scrapy,比如我想传递一个爬取的页码数目,我要每次爬取10页。
 
那么需要在spider中定义一个构造函数
 
    def __init__(self,page=None,*args, **kwargs):
super(Gaode,self).__init__(*args, **kwargs)
self.page=page


def start_requests(self):
XXXXXX 调用self.page 即可
yield Request(XXXX)

 
然后在启动scrapy的时候赋予参数的值:
 
scrapy crawl spider -a page=10
 
就可以动态传入参数
 
原创文章
转载请注明出处:http://30daydo.com/article/436
 

scrapyd 日志文件中文乱码 解决方案

python爬虫李魔佛 发表了文章 • 0 个评论 • 5820 次浏览 • 2019-03-27 17:13 • 来自相关话题

用网页打开scrapyd的后台管理页面后,选择日志,会发现里面的中文是乱码。即使下载下来看也是乱码。
网上一般的解决方法是修改scrapyd的源码,增加一个utf8的编码页面,需要重新写一个html的页面框架,对于一般只是看看日志的朋友来说,没必要这么大刀阔斧的。
 
可以直接使用postman来打开日志文件,里面的中文是正常的。





  查看全部
用网页打开scrapyd的后台管理页面后,选择日志,会发现里面的中文是乱码。即使下载下来看也是乱码。
网上一般的解决方法是修改scrapyd的源码,增加一个utf8的编码页面,需要重新写一个html的页面框架,对于一般只是看看日志的朋友来说,没必要这么大刀阔斧的。
 
可以直接使用postman来打开日志文件,里面的中文是正常的。

scrapyd.PNG

 

最新版的anaconda无法使用pip安装软件:报错 SSL module is not available

李魔佛 发表了文章 • 0 个评论 • 7442 次浏览 • 2019-03-21 14:06 • 来自相关话题

错误信息:CondaHTTPError: HTTP 000 CONNECTION FAILED for url <https://mirrors.ustc.edu.cn/an ... gt%3B
Elapsed: -

An HTTP error occurred when trying to retrieve this URL.
HTTP errors are often intermittent, and a simple retry will get you on your way.
SSLError(MaxRetryError('HTTPSConnectionPool(host=\'mirrors.ustc.edu.cn\', port=443): Max retries exceeded with url: /anaconda/cloud/conda-forge/win-64/repodata.json (Caused by SSLError("Can\'t connect to HTTPS URL because the SSL module is not available."))'))
折腾了很久,最新版的anaconda使用的是python3.7,也按照网上的方法,把openssl安装了,可是问题还是没有得到解决。
 
无奈下只能下载其他版本的anaconda。 可以到这里下载:
https://mirrors.tuna.tsinghua.edu.cn/anaconda/archive/ 
下载一个旧版本的anaconda,然后问题就得到解决了。
 
 
############ 更新 ############## 
 
新建一个 .condarc 文件,在 windows下的用户名目录下 ,  如 administrator下,
输入以下的内容:
 
channels:
- http://mirrors.tuna.tsinghua.e ... main/
- http://mirrors.tuna.tsinghua.e ... onda/
- http://mirrors.tuna.tsinghua.e ... free/
show_channel_urls: true
ssl_verify: true
重新下载即可。 查看全部
错误信息:
CondaHTTPError: HTTP 000 CONNECTION FAILED for url <https://mirrors.ustc.edu.cn/an ... gt%3B
Elapsed: -

An HTTP error occurred when trying to retrieve this URL.
HTTP errors are often intermittent, and a simple retry will get you on your way.
SSLError(MaxRetryError('HTTPSConnectionPool(host=\'mirrors.ustc.edu.cn\', port=443): Max retries exceeded with url: /anaconda/cloud/conda-forge/win-64/repodata.json (Caused by SSLError("Can\'t connect to HTTPS URL because the SSL module is not available."))'))

折腾了很久,最新版的anaconda使用的是python3.7,也按照网上的方法,把openssl安装了,可是问题还是没有得到解决。
 
无奈下只能下载其他版本的anaconda。 可以到这里下载:
https://mirrors.tuna.tsinghua.edu.cn/anaconda/archive/ 
下载一个旧版本的anaconda,然后问题就得到解决了。
 
 
############ 更新 ############## 
 
新建一个 .condarc 文件,在 windows下的用户名目录下 ,  如 administrator下,
输入以下的内容:
 
channels:
- http://mirrors.tuna.tsinghua.e ... main/
- http://mirrors.tuna.tsinghua.e ... onda/
- http://mirrors.tuna.tsinghua.e ... free/
show_channel_urls: true
ssl_verify: true

重新下载即可。

shapely windows的安装方式

李魔佛 发表了文章 • 0 个评论 • 5979 次浏览 • 2019-03-19 16:21 • 来自相关话题

在win7上默认使用pip 安装会失败。
报错:
pip install Shapely
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd5 in position 24: invalid continuation byte
应该是版本兼容问题。 到官网上:https://shapely.readthedocs.io/en/latest/project.html#requirements
发现,windows只能使用源文件安装或者使用conda安装。
 
 
源文件安装:
先下载
下载链接:
https://www.lfd.uci.edu/~gohlke/pythonlibs/#shapely 
 
然后使用pip安装
  查看全部
在win7上默认使用pip 安装会失败。
报错:
pip install Shapely
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd5 in position 24: invalid continuation byte

应该是版本兼容问题。 到官网上:https://shapely.readthedocs.io/en/latest/project.html#requirements
发现,windows只能使用源文件安装或者使用conda安装。
 
 
源文件安装:
先下载
下载链接:
https://www.lfd.uci.edu/~gohlke/pythonlibs/#shapely 
 
然后使用pip安装
 

踩坑了

Freedom 发表了文章 • 0 个评论 • 2475 次浏览 • 2019-03-19 00:22 • 来自相关话题

flask  循环导入的问题
flask  循环导入的问题

Linux下自制有道词典 - python 解密有道词典JS加密

python爬虫李魔佛 发表了文章 • 0 个评论 • 9802 次浏览 • 2019-02-23 20:17 • 来自相关话题

对于爬虫新手来说,JS解密是一道过不去的坎,需要不断地练习。
平时在linux下开发,鉴于没有什么好用翻译软件,打开网易也占用系统资源,所以写了个在控制台的翻译软件接口。
 
使用python爬虫,查看网页的JS加密方法,一步一步地分析,就能够得到最后的加密方法啦。
 
直接给出代码:
 # -*- coding: utf-8 -*-
# website: http://30daydo.com
# @Time : 2019/2/23 19:34
# @File : youdao.py
# 解密有道词典的JS


import hashlib
import random
import requests
import time


def md5_(word):
s = bytes(word, encoding='utf8')
m = hashlib.md5()
m.update(s)
ret = m.hexdigest()
return ret

def get_sign(word, salt):
ret = md5_('fanyideskweb' + word + salt + 'p09@Bn{h02_BIEe]$P^nG')
return ret


def youdao(word):
url = 'http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'
headers = {
'Host': 'fanyi.youdao.com',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0',
'Accept': 'application/json, text/javascript, */*; q=0.01',
'Accept-Language': 'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
'Accept-Encoding': 'gzip, deflate',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'X-Requested-With': 'XMLHttpRequest',
'Referer': 'http://fanyi.youdao.com/',
'Content-Length': '252',
'Cookie': 'YOUDAO_MOBILE_ACCESS_TYPE=1; OUTFOX_SEARCH_USER_ID=1672542763@10.169.0.83; JSESSIONID=aaaWzxpjeDu1gbhopLzKw; ___rl__test__cookies=1550913722828; OUTFOX_SEARCH_USER_ID_NCOO=372126049.6326876',
'Connection': 'keep-alive',
'Pragma': 'no-cache',
'Cache-Control': 'no-cache',
}

ts = str(int(time.time()*1000))
salt=ts+str(random.randint(0,10))
bv = md5_("5.0 (Windows)")
sign= get_sign(word,salt)

post_data = {
'i': word,
'from': 'AUTO', 'to': 'AUTO', 'smartresult': 'dict', 'client': 'fanyideskweb', 'salt': salt,
'sign': sign, 'ts': ts, 'bv': bv, 'doctype': 'json', 'version': '2.1',
'keyfrom': 'fanyi.web', 'action': 'FY_BY_REALTIME', 'typoResult': 'false'
}

r = requests.post(
url=url,
headers=headers,
data=post_data
)

for item in r.json().get('smartResult',{}).get('entries'):
print(item)

word='student'
youdao(word)
得到结果:





 
Github:
https://github.com/Rockyzsu/CrawlMan/tree/master/youdao_dictionary
原创文章,转载请注明出处
http://30daydo.com/article/416 查看全部
对于爬虫新手来说,JS解密是一道过不去的坎,需要不断地练习。
平时在linux下开发,鉴于没有什么好用翻译软件,打开网易也占用系统资源,所以写了个在控制台的翻译软件接口。
 
使用python爬虫,查看网页的JS加密方法,一步一步地分析,就能够得到最后的加密方法啦。
 
直接给出代码:
 
# -*- coding: utf-8 -*-
# website: http://30daydo.com
# @Time : 2019/2/23 19:34
# @File : youdao.py
# 解密有道词典的JS


import hashlib
import random
import requests
import time


def md5_(word):
s = bytes(word, encoding='utf8')
m = hashlib.md5()
m.update(s)
ret = m.hexdigest()
return ret

def get_sign(word, salt):
ret = md5_('fanyideskweb' + word + salt + 'p09@Bn{h02_BIEe]$P^nG')
return ret


def youdao(word):
url = 'http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'
headers = {
'Host': 'fanyi.youdao.com',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0',
'Accept': 'application/json, text/javascript, */*; q=0.01',
'Accept-Language': 'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
'Accept-Encoding': 'gzip, deflate',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'X-Requested-With': 'XMLHttpRequest',
'Referer': 'http://fanyi.youdao.com/',
'Content-Length': '252',
'Cookie': 'YOUDAO_MOBILE_ACCESS_TYPE=1; OUTFOX_SEARCH_USER_ID=1672542763@10.169.0.83; JSESSIONID=aaaWzxpjeDu1gbhopLzKw; ___rl__test__cookies=1550913722828; OUTFOX_SEARCH_USER_ID_NCOO=372126049.6326876',
'Connection': 'keep-alive',
'Pragma': 'no-cache',
'Cache-Control': 'no-cache',
}

ts = str(int(time.time()*1000))
salt=ts+str(random.randint(0,10))
bv = md5_("5.0 (Windows)")
sign= get_sign(word,salt)

post_data = {
'i': word,
'from': 'AUTO', 'to': 'AUTO', 'smartresult': 'dict', 'client': 'fanyideskweb', 'salt': salt,
'sign': sign, 'ts': ts, 'bv': bv, 'doctype': 'json', 'version': '2.1',
'keyfrom': 'fanyi.web', 'action': 'FY_BY_REALTIME', 'typoResult': 'false'
}

r = requests.post(
url=url,
headers=headers,
data=post_data
)

for item in r.json().get('smartResult',{}).get('entries'):
print(item)

word='student'
youdao(word)

得到结果:

youdao.PNG

 
Github:
https://github.com/Rockyzsu/CrawlMan/tree/master/youdao_dictionary
原创文章,转载请注明出处
http://30daydo.com/article/416

这周完成基础

Freedom 发表了文章 • 0 个评论 • 3086 次浏览 • 2019-02-20 00:25 • 来自相关话题

不轻易定计划,也不轻易改变计划
 
做事要坚持,切不可三心二意半途而废
 
时间管理上执行力还不够,闹钟响起就应该立马去做
 
在自律和随心上徘徊过好久
最终方知,自律方自由
 
 
-----------------------------2019.2.24  19:01------------------------------------------






意外事件耽误3天
周六日两天补上进度
还是按计划每天进行点轻松
浪费了杭州难得的艳阳天
最后两节 Jupyter   跳了 
 

  查看全部
1.png

不轻易定计划,也不轻易改变计划
 
做事要坚持,切不可三心二意半途而废
 
时间管理上执行力还不够,闹钟响起就应该立马去做
 
在自律和随心上徘徊过好久
最终方知,自律方自由
 
 
-----------------------------2019.2.24  19:01------------------------------------------

1.png


意外事件耽误3天
周六日两天补上进度
还是按计划每天进行点轻松
浪费了杭州难得的艳阳天
最后两节 Jupyter   跳了 
 

 

imutils resize的用法

李魔佛 发表了文章 • 0 个评论 • 12795 次浏览 • 2019-02-02 14:26 • 来自相关话题

imutils这个库主要对cv2做了简单的封装,是函数用起来更加友好。
imutils.resize(img,height=xx,width=xxx)
修改图像的大小。 这个函数会根据图片的比例进行重新绘制大小,如果你的图片是200:200的图片比例,那么如果你使用resize函数的时候,resize(img,height=50,width=20) 那么最后修改的图像是已最小的那个数字对齐,也就是width=20,所以最后出来的图片大小是20*20,而不是50*20,或者50*50.
  查看全部
imutils这个库主要对cv2做了简单的封装,是函数用起来更加友好。
imutils.resize(img,height=xx,width=xxx)
修改图像的大小。 这个函数会根据图片的比例进行重新绘制大小,如果你的图片是200:200的图片比例,那么如果你使用resize函数的时候,resize(img,height=50,width=20) 那么最后修改的图像是已最小的那个数字对齐,也就是width=20,所以最后出来的图片大小是20*20,而不是50*20,或者50*50.
 

scrapy response转化为图片

python爬虫李魔佛 发表了文章 • 0 个评论 • 4847 次浏览 • 2019-02-01 14:39 • 来自相关话题

scrapy使用Request函数,URL为一个图片地址,那么返回的response是一个图片的bytes,使用response.text是无法获取到内容的,需要使用response.body, 返回一个b'xxxxxxxxxxxxxxxxx'的字节内容,然后直接把这个字节内容保存为图片即可:
with open('temp.jpg','wb') as f:
    f.write(reponse.body)
 
即可。
  查看全部
scrapy使用Request函数,URL为一个图片地址,那么返回的response是一个图片的bytes,使用response.text是无法获取到内容的,需要使用response.body, 返回一个b'xxxxxxxxxxxxxxxxx'的字节内容,然后直接把这个字节内容保存为图片即可:
with open('temp.jpg','wb') as f:
    f.write(reponse.body)
 
即可。
 

python 中文图片文字识别

李魔佛 发表了文章 • 0 个评论 • 11622 次浏览 • 2019-02-01 10:47 • 来自相关话题

pytesseract这个库识别率偏低,也就菜鸟才会用。
使用方法很简单,安装好pytesseract(里面很多坑,小白的话不可避免要折腾一番),然后下载一个中文的字库,百度网盘:https://pan.baidu.com/s/1_jom2d95IeR40gsvkhUuvQ
 
然后把文件放到tesseract的文件夹中 C:\Program Files (x86)\Tesseract-OCR\tessdata 
然后就可以拿来识别了:
from PIL import Image
im = Image.open('chinese.jpg')
plt.figure(figsize=(20,20))
plt.imshow(im)

pytesseract.image_to_string(im,lang='chi_sim')
图片的内容是这样的:





 
然后识别效果如下:
 
'可L又使用以下的语句i上图片显示大 此'
还是不咋地。
 
那么可以换成大厂的API。试试百度的:
""" 读取图片 """
def get_file_content(filePath):
with open(filePath, 'rb') as fp:
return fp.read()

image = get_file_content('example.jpg')

""" 调用通用文字识别, 图片参数为本地图片 """
client.basicGeneral(image);

""" 如果有可选参数 """
options = {}
options["language_type"] = "CHN_ENG"
options["detect_direction"] = "true"
options["detect_language"] = "true"
options["probability"] = "true"

from aip import AipOcr

""" 你的 APPID AK SK """
APP_ID = '你的 App ID'
API_KEY = '你的 Api Key'
SECRET_KEY = '你的 Secret Key'

client = AipOcr(APP_ID, API_KEY, SECRET_KEY)


""" 带参数调用通用文字识别, 图片参数为本地图片 """
client.basicGeneral(image, options)

url = "https//www.x.com/sample.jpg"

""" 调用通用文字识别, 图片参数为远程url图片 """
client.basicGeneralUrl(url);

""" 如果有可选参数 """
options = {}
options["language_type"] = "CHN_ENG"
options["detect_direction"] = "true"
options["detect_language"] = "true"
options["probability"] = "true"

""" 带参数调用通用文字识别, 图片参数为远程url图片 """
client.basicGeneralUrl(url, options)
先去百度云申请一个API,免费的。
https://cloud.baidu.com/doc/OCR/OCR-Python-SDK.html#.E9.85.8D.E7.BD.AEAipOcr
然后把key复制到上面的代码中就可以了。
 
然后再调用看看结果:
可以使用以下的语句让图片显示大些正确率明显高很多了。
 
 
 
  查看全部
pytesseract这个库识别率偏低,也就菜鸟才会用。
使用方法很简单,安装好pytesseract(里面很多坑,小白的话不可避免要折腾一番),然后下载一个中文的字库,百度网盘:https://pan.baidu.com/s/1_jom2d95IeR40gsvkhUuvQ
 
然后把文件放到tesseract的文件夹中 C:\Program Files (x86)\Tesseract-OCR\tessdata 
然后就可以拿来识别了:
from PIL import Image
im = Image.open('chinese.jpg')
plt.figure(figsize=(20,20))
plt.imshow(im)

pytesseract.image_to_string(im,lang='chi_sim')

图片的内容是这样的:

中文1.JPG

 
然后识别效果如下:
 
'可L又使用以下的语句i上图片显示大 此'

还是不咋地。
 
那么可以换成大厂的API。试试百度的:
""" 读取图片 """
def get_file_content(filePath):
with open(filePath, 'rb') as fp:
return fp.read()

image = get_file_content('example.jpg')

""" 调用通用文字识别, 图片参数为本地图片 """
client.basicGeneral(image);

""" 如果有可选参数 """
options = {}
options["language_type"] = "CHN_ENG"
options["detect_direction"] = "true"
options["detect_language"] = "true"
options["probability"] = "true"

from aip import AipOcr

""" 你的 APPID AK SK """
APP_ID = '你的 App ID'
API_KEY = '你的 Api Key'
SECRET_KEY = '你的 Secret Key'

client = AipOcr(APP_ID, API_KEY, SECRET_KEY)


""" 带参数调用通用文字识别, 图片参数为本地图片 """
client.basicGeneral(image, options)

url = "https//www.x.com/sample.jpg"

""" 调用通用文字识别, 图片参数为远程url图片 """
client.basicGeneralUrl(url);

""" 如果有可选参数 """
options = {}
options["language_type"] = "CHN_ENG"
options["detect_direction"] = "true"
options["detect_language"] = "true"
options["probability"] = "true"

""" 带参数调用通用文字识别, 图片参数为远程url图片 """
client.basicGeneralUrl(url, options)

先去百度云申请一个API,免费的。
https://cloud.baidu.com/doc/OCR/OCR-Python-SDK.html#.E9.85.8D.E7.BD.AEAipOcr
然后把key复制到上面的代码中就可以了。
 
然后再调用看看结果:
可以使用以下的语句让图片显示大些
正确率明显高很多了。
 
 
 
 

jupyter notebook 修改plt显示的图片大小

李魔佛 发表了文章 • 0 个评论 • 16993 次浏览 • 2019-02-01 09:17 • 来自相关话题

默认在jupyter notebook中显示的图片都比较小,导致看不清楚。
可以使用以下的语句让图片显示大一些:
 
im = Image.open('chinese.png')
plt.figure(figsize=(20,20))
plt.imshow(im)
  查看全部
默认在jupyter notebook中显示的图片都比较小,导致看不清楚。
可以使用以下的语句让图片显示大一些:
 
im = Image.open('chinese.png')
plt.figure(figsize=(20,20))
plt.imshow(im)

 

拉勾网的反爬策略

python爬虫李魔佛 发表了文章 • 0 个评论 • 4926 次浏览 • 2019-01-23 10:18 • 来自相关话题

更新于2019-01-23 ************
(请注意日期,因为不保证往后的日子里面反爬策略还有效)
 
1. 封IP,这个没的说,肯定要使用代理IP
2. scrapy里面的需要添加headers,而headers中一定要加上Cookies的数据。 之前要做Request中的cookies参数添加cookies,现在发现失效了,只能在headers中添加cookies数据。
 
headers = {'Accept': 'application/json,text/javascript,*/*;q=0.01', 'Accept-Encoding':
'gzip,deflate,br',
'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8', 'Cache-Control': 'no-cache',
# 'Connection': 'keep-alive',
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
'Cookie': 'JSESSIONID=ABAAABAABEEAAJAACF8F22F99AFA35F9EEC28F2D0E46A41;_ga=GA1.2.331323650.1548204973;_gat=1;Hm_lvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1548204973;user_trace_token=20190123085612-adf35b62-1ea9-11e9-b744-5254005c3644;LGSID=20190123085612-adf35c69-1ea9-11e9-b744-5254005c3644;PRE_UTM=;PRE_HOST=;PRE_SITE=;PRE_LAND=https%3A%2F%2Fwww.lagou.com%2F;LGUID=20190123085612-adf35ed5-1ea9-11e9-b744-5254005c3644;_gid=GA1.2.1809874038.1548204973;index_location_city=%E6%B7%B1%E5%9C%B3;TG-TRACK-CODE=index_search;SEARCH_ID=169bf76c08b548f8830967a1968d10ca;Hm_lpvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1548204985;LGRID=20190123085624-b52a0555-1ea9-11e9-b744-5254005c3644',
'Host': 'www.lagou.com', 'Origin': 'https://www.lagou.com', 'Pragma': 'no-cache',
'Referer': 'https://www.lagou.com/jobs/list_%E7%88%AC%E8%99%AB?labelWords=&fromSearch=true&suginput=',
'User-Agent': 'Mozilla/5.0(WindowsNT6.3;WOW64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/71.0.3578.98Safari/537.36',
'X-Anit-Forge-Code': '0',
'X-Anit-Forge-Token': 'None',
'X-Requested-With': 'XMLHttpRequest'
} 查看全部
更新于2019-01-23 ************
(请注意日期,因为不保证往后的日子里面反爬策略还有效)
 
1. 封IP,这个没的说,肯定要使用代理IP
2. scrapy里面的需要添加headers,而headers中一定要加上Cookies的数据。 之前要做Request中的cookies参数添加cookies,现在发现失效了,只能在headers中添加cookies数据。
 
   headers = {'Accept': 'application/json,text/javascript,*/*;q=0.01', 'Accept-Encoding':
'gzip,deflate,br',
'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8', 'Cache-Control': 'no-cache',
# 'Connection': 'keep-alive',
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
'Cookie': 'JSESSIONID=ABAAABAABEEAAJAACF8F22F99AFA35F9EEC28F2D0E46A41;_ga=GA1.2.331323650.1548204973;_gat=1;Hm_lvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1548204973;user_trace_token=20190123085612-adf35b62-1ea9-11e9-b744-5254005c3644;LGSID=20190123085612-adf35c69-1ea9-11e9-b744-5254005c3644;PRE_UTM=;PRE_HOST=;PRE_SITE=;PRE_LAND=https%3A%2F%2Fwww.lagou.com%2F;LGUID=20190123085612-adf35ed5-1ea9-11e9-b744-5254005c3644;_gid=GA1.2.1809874038.1548204973;index_location_city=%E6%B7%B1%E5%9C%B3;TG-TRACK-CODE=index_search;SEARCH_ID=169bf76c08b548f8830967a1968d10ca;Hm_lpvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1548204985;LGRID=20190123085624-b52a0555-1ea9-11e9-b744-5254005c3644',
'Host': 'www.lagou.com', 'Origin': 'https://www.lagou.com', 'Pragma': 'no-cache',
'Referer': 'https://www.lagou.com/jobs/list_%E7%88%AC%E8%99%AB?labelWords=&fromSearch=true&suginput=',
'User-Agent': 'Mozilla/5.0(WindowsNT6.3;WOW64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/71.0.3578.98Safari/537.36',
'X-Anit-Forge-Code': '0',
'X-Anit-Forge-Token': 'None',
'X-Requested-With': 'XMLHttpRequest'
}

python高手才知道的答案

李魔佛 发表了文章 • 0 个评论 • 3133 次浏览 • 2019-01-22 21:51 • 来自相关话题

记录一些python不为人知的有趣的用法或者知识点
 
1. >>> a = "some_string"
>>> id(a)
140420665652016
>>> id("some" + "_" + "string") # 注意两个的id值是相同的.
140420665652016
 2.e = "wtf"
f = "wtf"
e is f
结果 True e = "wtf?"
f = "wtf?"
e is f
结果 False
3.some_dict = {}
some_dict[5.5] = "Ruby"
some_dict[5.0] = "JavaScript"
some_dict[5] = "Python" >>> some_dict[5.5]
"Ruby"
>>> some_dict[5.0]
"Python"
>>> some_dict[5]
"Python"
Python 字典通过检查键值是否相等和比较哈希值来确定两个键是否相同.
具有相同值的不可变对象在Python中始终具有相同的哈希值.
 
4. 到处返回def some_func():
try:
return 'from_try'
finally:
return 'from_finally' >>> some_func()
'from_finally'
当在 "try...finally" 语句的 try 中执行 return, break 或 continue 后, finally 子句依然会执行.
函数的返回值由最后执行的 return 语句决定. 由于 finally 子句一定会执行, 所以 finally 子句中的 return 将始终是最后执行的语句.
 
5for i in range(4):
print(i)
i = 10你可曾觉得这个循环只会运行一次?

0 1 2 3
由于循环在Python中工作方式, 赋值语句 i = 10 并不会影响迭代循环, 在每次迭代开始之前, 迭代器(这里指 range(4)) 生成的下一个元素就被解包并赋值给目标列表的变量(这里指 i)了. 查看全部
记录一些python不为人知的有趣的用法或者知识点
 
1. 
>>> a = "some_string"
>>> id(a)
140420665652016
>>> id("some" + "_" + "string") # 注意两个的id值是相同的.
140420665652016

 2.
e = "wtf"
f = "wtf"
e is f
结果 True
 
e = "wtf?"
f = "wtf?"
e is f
结果 False

3.
some_dict = {}
some_dict[5.5] = "Ruby"
some_dict[5.0] = "JavaScript"
some_dict[5] = "Python"
 
>>> some_dict[5.5]
"Ruby"
>>> some_dict[5.0]
"Python"
>>> some_dict[5]
"Python"

Python 字典通过检查键值是否相等和比较哈希值来确定两个键是否相同.
具有相同值的不可变对象在Python中始终具有相同的哈希值.
 
4. 到处返回
def some_func():
try:
return 'from_try'
finally:
return 'from_finally'
 
>>> some_func()
'from_finally'

当在 "try...finally" 语句的 try 中执行 return, break 或 continue 后, finally 子句依然会执行.
函数的返回值由最后执行的 return 语句决定. 由于 finally 子句一定会执行, 所以 finally 子句中的 return 将始终是最后执行的语句.
 
5
for i in range(4):
print(i)
i = 10
你可曾觉得这个循环只会运行一次?

0 1 2 3
由于循环在Python中工作方式, 赋值语句 i = 10 并不会影响迭代循环, 在每次迭代开始之前, 迭代器(这里指 range(4)) 生成的下一个元素就被解包并赋值给目标列表的变量(这里指 i)了.

numpy 二维数组按列合并

李魔佛 发表了文章 • 0 个评论 • 7586 次浏览 • 2019-01-19 21:43 • 来自相关话题

numpy的数组默认按行合并,如何按列合并?
 
先生产测试数组# np 的运算
n = np.arange(1,17)
转化形态:
n0 = n.reshape(4,4)变成4x4的矩阵
array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12],
[13, 14, 15, 16]])
然后运用concatenate函数拼接:
np.concatenate((n0,n0),axis=1)array([[ 1, 2, 3, 4, 1, 2, 3, 4], [ 5, 6, 7, 8, 5, 6, 7, 8], [ 9, 10, 11, 12, 9, 10, 11, 12], [13, 14, 15, 16, 13, 14, 15, 16]])
 这个只需要添加参数axis=1就可以了,axis默认是为0,按照行拼接。
np.concatenate((n0,n0),axis=1)
array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12],
[13, 14, 15, 16],
[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12],
[13, 14, 15, 16]]) 查看全部
numpy的数组默认按行合并,如何按列合并?
 
先生产测试数组
# np 的运算
n = np.arange(1,17)

转化形态:
n0 = n.reshape(4,4)
变成4x4的矩阵
array([[ 1,  2,  3,  4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12],
[13, 14, 15, 16]])

然后运用concatenate函数拼接:
np.concatenate((n0,n0),axis=1)
array([[ 1, 2, 3, 4, 1, 2, 3, 4], [ 5, 6, 7, 8, 5, 6, 7, 8], [ 9, 10, 11, 12, 9, 10, 11, 12], [13, 14, 15, 16, 13, 14, 15, 16]])

 这个只需要添加参数axis=1就可以了,axis默认是为0,按照行拼接。
np.concatenate((n0,n0),axis=1)

array([[ 1,  2,  3,  4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12],
[13, 14, 15, 16],
[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12],
[13, 14, 15, 16]])

Django2.0+ 加载本地JS文件 配置

李魔佛 发表了文章 • 0 个评论 • 5202 次浏览 • 2019-01-15 10:25 • 来自相关话题

搜索网络上的,貌似有几种方案,不过都是坑,运行返回404,无法找到js文件的。 以下是自己亲测车工的。
 本地调试,把JS存放本地,可以加快调试速度,不然每次都从CDN上取,影响效率,且无法离线运行
(没有网络的情况下)。
 
环境:python3.6 + Django 2.1.5
 
文件结构:





 
在django项目根目录,创建一个static的目录,里面存放一个jquery.js 的文件(这个文件可以到官方下载),然后在settings.py里面配置:
 
setting.py
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static/'),
)
 
然后在模板文件 test.html中引用:
 
<!DOCTYPE html>
{% load staticfiles %}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>交割单查询</title>
<script type="text/javascript" src="{% static 'jquery.js' %}"></script>
然后重新运行django,就可以了。 查看全部
搜索网络上的,貌似有几种方案,不过都是坑,运行返回404,无法找到js文件的。 以下是自己亲测车工的。
 本地调试,把JS存放本地,可以加快调试速度,不然每次都从CDN上取,影响效率,且无法离线运行
(没有网络的情况下)。
 
环境:python3.6 + Django 2.1.5
 
文件结构:

1123.png

 
在django项目根目录,创建一个static的目录,里面存放一个jquery.js 的文件(这个文件可以到官方下载),然后在settings.py里面配置:
 
setting.py
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static/'),
)

 
然后在模板文件 test.html中引用:
 
<!DOCTYPE html>
{% load staticfiles %}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>交割单查询</title>
<script type="text/javascript" src="{% static 'jquery.js' %}"></script>

然后重新运行django,就可以了。

python的表达式执行顺序

李魔佛 发表了文章 • 0 个评论 • 2891 次浏览 • 2019-01-10 16:06 • 来自相关话题

-1<2==1这个在python里的结果是什么?
 
答案是False





 
why ?
 
因为你要把表达式分开来看
1<2 and 2==1
这样就可以看出问题了。
True and False
那么答案就是False了。
  查看全部
-1<2==1
这个在python里的结果是什么?
 
答案是False

result.JPG

 
why ?
 
因为你要把表达式分开来看
1<2 and 2==1
这样就可以看出问题了。
True and False
那么答案就是False了。
 

发现一个好玩的python脚本,你家小公主一定喜欢哈

李魔佛 发表了文章 • 0 个评论 • 4302 次浏览 • 2019-01-10 15:28 • 来自相关话题

 
#coding:utf-8
from turtle import *

def nose(x,y):#鼻子
penup()#提起笔
goto(x,y)#定位
pendown()#落笔,开始画
setheading(-30)#将乌龟的方向设置为to_angle/为数字(0-东、90-北、180-西、270-南)
begin_fill()#准备开始填充图形
a=0.4
for i in range(120):
if 0<=i<30 or 60<=i<90:
a=a+0.08
left(3) #向左转3度
forward(a) #向前走a的步长
else:
a=a-0.08
left(3)
forward(a)
end_fill()#填充完成

penup()
setheading(90)
forward(25)
setheading(0)
forward(10)
pendown()
pencolor(255,155,192)#画笔颜色
setheading(10)
begin_fill()
circle(5)
color(160,82,45)#返回或设置pencolor和fillcolor
end_fill()

penup()
setheading(0)
forward(20)
pendown()
pencolor(255,155,192)
setheading(10)
begin_fill()
circle(5)
color(160,82,45)
end_fill()


def head(x,y):#头
color((255,155,192),"pink")
penup()
goto(x,y)
setheading(0)
pendown()
begin_fill()
setheading(180)
circle(300,-30)
circle(100,-60)
circle(80,-100)
circle(150,-20)
circle(60,-95)
setheading(161)
circle(-300,15)
penup()
goto(-100,100)
pendown()
setheading(-30)
a=0.4
for i in range(60):
if 0<=i<30 or 60<=i<90:
a=a+0.08
lt(3) #向左转3度
fd(a) #向前走a的步长
else:
a=a-0.08
lt(3)
fd(a)
end_fill()


def ears(x,y): #耳朵
color((255,155,192),"pink")
penup()
goto(x,y)
pendown()
begin_fill()
setheading(100)
circle(-50,50)
circle(-10,120)
circle(-50,54)
end_fill()

penup()
setheading(90)
forward(-12)
setheading(0)
forward(30)
pendown()
begin_fill()
setheading(100)
circle(-50,50)
circle(-10,120)
circle(-50,56)
end_fill()


def eyes(x,y):#眼睛
color((255,155,192),"white")
penup()
setheading(90)
forward(-20)
setheading(0)
forward(-95)
pendown()
begin_fill()
circle(15)
end_fill()

color("black")
penup()
setheading(90)
forward(12)
setheading(0)
forward(-3)
pendown()
begin_fill()
circle(3)
end_fill()

color((255,155,192),"white")
penup()
seth(90)
forward(-25)
seth(0)
forward(40)
pendown()
begin_fill()
circle(15)
end_fill()

color("black")
penup()
setheading(90)
forward(12)
setheading(0)
forward(-3)
pendown()
begin_fill()
circle(3)
end_fill()


def cheek(x,y):#腮
color((255,155,192))
penup()
goto(x,y)
pendown()
setheading(0)
begin_fill()
circle(30)
end_fill()


def mouth(x,y): #嘴
color(239,69,19)
penup()
goto(x,y)
pendown()
setheading(-80)
circle(30,40)
circle(40,80)

def body(x,y):#身体
color("red",(255,99,71))
penup()
goto(x,y)
pendown()
begin_fill()
setheading(-130)
circle(100,10)
circle(300,30)
setheading(0)
forward(230)
setheading(90)
circle(300,30)
circle(100,3)
color((255,155,192),(255,100,100))
setheading(-135)
circle(-80,63)
circle(-150,24)
end_fill()


def hands(x,y):#手
color((255,155,192))
penup()
goto(x,y)
pendown()
setheading(-160)
circle(300,15)
penup()
setheading(90)
forward(15)
setheading(0)
forward(0)
pendown()
setheading(-10)
circle(-20,90)

penup()
setheading(90)
forward(30)
setheading(0)
forward(237)
pendown()
setheading(-20)
circle(-300,15)
penup()
setheading(90)
forward(20)
setheading(0)
forward(0)
pendown()
setheading(-170)
circle(20,90)

def foot(x,y):#脚
pensize(10)
color((240,128,128))
penup()
goto(x,y)
pendown()
setheading(-90)
forward(40)
setheading(-180)
color("black")
pensize(15)
fd(20)

pensize(10)
color((240,128,128))
penup()
setheading(90)
forward(40)
setheading(0)
forward(90)
pendown()
setheading(-90)
forward(40)
setheading(-180)
color("black")
pensize(15)
fd(20)

def tail(x,y):#尾巴
pensize(4)
color((255,155,192))
penup()
goto(x,y)
pendown()
seth(0)
circle(70,20)
circle(10,330)
circle(70,30)

def setting(): #参数设置
pensize(4)
hideturtle() #使乌龟无形(隐藏)
colormode(255) #将其设置为1.0或255.随后 颜色三元组的r,g,b值必须在0 .. cmode范围内
color((255,155,192),"pink")
setup(840,500)
speed(10)

def main():
setting() #画布、画笔设置
nose(-100,100) #鼻子
head(-69,167) #头
ears(0,160) #耳朵
eyes(0,140) #眼睛
cheek(80,10) #腮
mouth(-20,30) #嘴
body(-32,-8) #身体
hands(-56,-45) #手
foot(2,-177) #脚
tail(148,-155) #尾巴
done()

if __name__ == '__main__':
main()
安装turtle
pip install turtle
然后运行上面代码即可哈。
  查看全部
 
#coding:utf-8
from turtle import *

def nose(x,y):#鼻子
penup()#提起笔
goto(x,y)#定位
pendown()#落笔,开始画
setheading(-30)#将乌龟的方向设置为to_angle/为数字(0-东、90-北、180-西、270-南)
begin_fill()#准备开始填充图形
a=0.4
for i in range(120):
if 0<=i<30 or 60<=i<90:
a=a+0.08
left(3) #向左转3度
forward(a) #向前走a的步长
else:
a=a-0.08
left(3)
forward(a)
end_fill()#填充完成

penup()
setheading(90)
forward(25)
setheading(0)
forward(10)
pendown()
pencolor(255,155,192)#画笔颜色
setheading(10)
begin_fill()
circle(5)
color(160,82,45)#返回或设置pencolor和fillcolor
end_fill()

penup()
setheading(0)
forward(20)
pendown()
pencolor(255,155,192)
setheading(10)
begin_fill()
circle(5)
color(160,82,45)
end_fill()


def head(x,y):#头
color((255,155,192),"pink")
penup()
goto(x,y)
setheading(0)
pendown()
begin_fill()
setheading(180)
circle(300,-30)
circle(100,-60)
circle(80,-100)
circle(150,-20)
circle(60,-95)
setheading(161)
circle(-300,15)
penup()
goto(-100,100)
pendown()
setheading(-30)
a=0.4
for i in range(60):
if 0<=i<30 or 60<=i<90:
a=a+0.08
lt(3) #向左转3度
fd(a) #向前走a的步长
else:
a=a-0.08
lt(3)
fd(a)
end_fill()


def ears(x,y): #耳朵
color((255,155,192),"pink")
penup()
goto(x,y)
pendown()
begin_fill()
setheading(100)
circle(-50,50)
circle(-10,120)
circle(-50,54)
end_fill()

penup()
setheading(90)
forward(-12)
setheading(0)
forward(30)
pendown()
begin_fill()
setheading(100)
circle(-50,50)
circle(-10,120)
circle(-50,56)
end_fill()


def eyes(x,y):#眼睛
color((255,155,192),"white")
penup()
setheading(90)
forward(-20)
setheading(0)
forward(-95)
pendown()
begin_fill()
circle(15)
end_fill()

color("black")
penup()
setheading(90)
forward(12)
setheading(0)
forward(-3)
pendown()
begin_fill()
circle(3)
end_fill()

color((255,155,192),"white")
penup()
seth(90)
forward(-25)
seth(0)
forward(40)
pendown()
begin_fill()
circle(15)
end_fill()

color("black")
penup()
setheading(90)
forward(12)
setheading(0)
forward(-3)
pendown()
begin_fill()
circle(3)
end_fill()


def cheek(x,y):#腮
color((255,155,192))
penup()
goto(x,y)
pendown()
setheading(0)
begin_fill()
circle(30)
end_fill()


def mouth(x,y): #嘴
color(239,69,19)
penup()
goto(x,y)
pendown()
setheading(-80)
circle(30,40)
circle(40,80)

def body(x,y):#身体
color("red",(255,99,71))
penup()
goto(x,y)
pendown()
begin_fill()
setheading(-130)
circle(100,10)
circle(300,30)
setheading(0)
forward(230)
setheading(90)
circle(300,30)
circle(100,3)
color((255,155,192),(255,100,100))
setheading(-135)
circle(-80,63)
circle(-150,24)
end_fill()


def hands(x,y):#手
color((255,155,192))
penup()
goto(x,y)
pendown()
setheading(-160)
circle(300,15)
penup()
setheading(90)
forward(15)
setheading(0)
forward(0)
pendown()
setheading(-10)
circle(-20,90)

penup()
setheading(90)
forward(30)
setheading(0)
forward(237)
pendown()
setheading(-20)
circle(-300,15)
penup()
setheading(90)
forward(20)
setheading(0)
forward(0)
pendown()
setheading(-170)
circle(20,90)

def foot(x,y):#脚
pensize(10)
color((240,128,128))
penup()
goto(x,y)
pendown()
setheading(-90)
forward(40)
setheading(-180)
color("black")
pensize(15)
fd(20)

pensize(10)
color((240,128,128))
penup()
setheading(90)
forward(40)
setheading(0)
forward(90)
pendown()
setheading(-90)
forward(40)
setheading(-180)
color("black")
pensize(15)
fd(20)

def tail(x,y):#尾巴
pensize(4)
color((255,155,192))
penup()
goto(x,y)
pendown()
seth(0)
circle(70,20)
circle(10,330)
circle(70,30)

def setting(): #参数设置
pensize(4)
hideturtle() #使乌龟无形(隐藏)
colormode(255) #将其设置为1.0或255.随后 颜色三元组的r,g,b值必须在0 .. cmode范围内
color((255,155,192),"pink")
setup(840,500)
speed(10)

def main():
setting() #画布、画笔设置
nose(-100,100) #鼻子
head(-69,167) #头
ears(0,160) #耳朵
eyes(0,140) #眼睛
cheek(80,10) #腮
mouth(-20,30) #嘴
body(-32,-8) #身体
hands(-56,-45) #手
foot(2,-177) #脚
tail(148,-155) #尾巴
done()

if __name__ == '__main__':
main()

安装turtle
pip install turtle
然后运行上面代码即可哈。
 

missing 1 required positional argument on_delete --Django2.0

李魔佛 发表了文章 • 0 个评论 • 3517 次浏览 • 2018-12-26 15:23 • 来自相关话题

Django2.0+
使用ForeignKey 报错
TypeError: __init__() missing 1 required positional argument: 'on_delete'

解决办法:from django.db import models
class Article(models.Model):
category = models.ForeignKey('Category', on_delete=models.PROTECT)
title = models.CharField(max_length=55)
# ...

def __str__(self):
return self.title
定义ForeignKey的时候添加参数on_delete,然后需要重新migration model,不然还是会报错。
(如果还是不行,把migration文件夹的内容全部删掉,在migrated一下) 查看全部
Django2.0+
使用ForeignKey 报错
TypeError: __init__() missing 1 required positional argument: 'on_delete'

解决办法:
from django.db import models
class Article(models.Model):
category = models.ForeignKey('Category', on_delete=models.PROTECT)
title = models.CharField(max_length=55)
# ...

def __str__(self):
return self.title

定义ForeignKey的时候添加参数on_delete,然后需要重新migration model,不然还是会报错。
(如果还是不行,把migration文件夹的内容全部删掉,在migrated一下)