Coder Social home page Coder Social logo

python3-cookbook's Introduction

GitHub issues License Github downloads GitHub release

《Python Cookbook in Chinese》 3rd Edition 翻译

《Python Cookbook》3rd 中文版3.0.0正式发布啦 ^_^! ——2017/12/07

在线阅读地址:http://python3-cookbook.readthedocs.org/zh_CN/latest/

最新版(3.0.0)下载

关于作者David Beazley

本书作者是David Beazley大神,一位独立的计算机科学家、教育家,以及有着35年开发经验的软件开发者。 他在Python社区一直都很活跃,编写了很多的python包, 发表了很多的公开演讲视频 以及 编程教程。 同时还是Python Essential Reference 以及 Python Cookbook (O'Reilly Media)的作者。

David Beazley大神的博客地址:http://www.dabeaz.com/

译者的话

人生苦短,我用Python!

译者一直坚持使用Python3,因为它代表了Python的未来。虽然向后兼容是它的硬伤,但是这个局面迟早会改变的, 而且Python3的未来需要每个人的帮助和支持。 目前市面上的教程书籍,网上的手册大部分基本都是2.x系列的,专门基于3.x系列的书籍少的可怜。

最近看到一本《Python Cookbook》3rd Edition,完全基于Python3,写的也很不错。 为了Python3的普及,我也不自量力,想做点什么事情。于是乎,就有了翻译这本书的冲动了! 这不是一项轻松的工作,却是一件值得做的工作:不仅方便了别人,而且对自己翻译能力也是一种锻炼和提升。

译者会坚持对自己每一句的翻译负责,力求高质量。但受能力限制,也难免有疏漏或者表意不当的地方。 如果译文中有什么错漏的地方请大家见谅,也欢迎大家随时指正。

目前已经正式完成了整本书的翻译工作,历时2年,不管怎样还是坚持下来了。现在共享给python社区。

欢迎关注我的个人公众号“飞污熊”,我会定期分享一些自己的Python学习笔记和心得。

公众号

项目说明

  • 所有文档均使用reStructuredText编辑,参考 reStructuredText
  • 当前文档生成托管在 readthedocs
  • 生成的文档预览地址: python3-cookbook
  • 使用了python官方文档主题 sphinx-rtd-theme ,也是默认的主题default.
  • 书中所有代码均在python 3.6版本下面运行通过,所有源码放在cookbook包下面
# on_rtd is whether we are on readthedocs.org, this line of code grabbed from docs.readthedocs.org
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'

if not on_rtd:  # only import and set the theme if we're building docs locally
    import sphinx_rtd_theme
    html_theme = 'sphinx_rtd_theme'
    html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]

# otherwise, readthedocs.org uses their theme by default, so no need to specify it

其他贡献者

排名不分先后:

  1. Yu Longjun (https://github.com/yulongjun)
  2. tylinux (https://github.com/tylinux)
  3. Kevin Guan (https://github.com/K-Guan)
  4. littlezz (https://github.com/littlezz)
  5. cclauss (https://github.com/cclauss)
  6. Yan Zhang (https://github.com/Eskibear)
  7. xiuyanduan (https://github.com/xiuyanduan)
  8. FPlust (https://github.com/fplust)
  9. lambdaplus (https://github.com/lambdaplus)
  10. Tony Yang ([email protected])

更多贡献者


关于源码生成PDF文件

有网友提问怎样通过源码生成PDF文件,由于这个步骤介绍有点长,不适合放在README里面, 我专门写了篇博客专门介绍怎样通过ReadtheDocs托管文档,怎样自己生成PDF文件,大家可以参考一下。

https://www.xncoding.com/2017/01/22/fullstack/readthedoc.html

另外关于生成的PDF文件中会自动生成标题编号的问题,有热心网友 CarlKing5019提出了解决方案, 请参考issues108:

#108

再次感谢每一位贡献者。


How to Contribute

You are welcome to contribute to the project as follow

  • fork project and commit pull requests
  • add/edit wiki
  • report/fix issue
  • code review
  • commit new feature
  • add testcase

Meanwhile you'd better follow the rules below

  • It's NOT recommended to submit a pull request directly to master branch. develop branch is more appropriate
  • Follow common Python coding conventions
  • Add the following license in each source file

License

(The Apache License)

Copyright (c) 2014-2018 Xiong Neng and other contributors

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

python3-cookbook's People

Contributors

0x4ec7 avatar basefas avatar caimaoy avatar carlking5019 avatar eskibear avatar everfighting avatar fanofxiaofeng avatar finfou avatar flynnon avatar fplust avatar k-guan avatar kerwincsc avatar kisesy avatar kyan001 avatar lambdaplus avatar littlezz avatar papdpcpd avatar protodonuts avatar rksys avatar robertding avatar sdygt avatar seagoat avatar tianshoulong1988 avatar tylinux avatar void285 avatar woshihuo12 avatar xiuyanduan avatar yelynn0401 avatar yidao620c avatar zlu27 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

python3-cookbook's Issues

14.9节 错别字

解决问题 类目下第三段

在回溯中科院看到,两个异常都被捕获。 要想捕获这样的异常,你可以使用一个简单的 except 语句。 不过,你还可以通过查看异常对象的 cause 属性来跟踪异常链。例如

科院 应该为 可以

6.11读写二进制数组数据的一个小缩进错误

首先对作者们表示感谢,这本书不错,翻译的也不错,节省了自己不少时间
在讲到利用collections模块中的namedtuple的示例中:

from collections import namedtuple

Record = namedtuple('Record', ['kind','x','y'])

with open('data.p', 'rb') as f:
    records = (Record(*r) for r in read_records('<idd', f))

for r in records:
    print(r.kind, r.x, r.y)

for r in records:的缩进错了,此时文件已经关闭,运行会提示ValueError: read of closed file.
应该修改成下面的:

from collections import namedtuple

Record = namedtuple('Record', ['kind','x','y'])

with open('data.p', 'rb') as f:
    records = (Record(*r) for r in read_records('<idd', f))

    for r in records:
        print(r.kind, r.x, r.y)

4.16小节关于“使用iter() 来代替”的一个小问题

翻译中的代码片段为:

def reader2(s):
    for chunk in iter(lambda: s.recv(CHUNKSIZE), b''):
        pass
        # process_data(data)

为与本节使用while循环的例子保持一致,并作为对照,建议可否做如下修改:

def reader2(s):
    for data in iter(lambda: s.recv(CHUNKSIZE), b''):
        process_data(data)

1.3 保留最后N个元素 中的一个翻译问题

先附上英文原文:

For example, the following code performs a simple text match on a sequence of lines and yields the
matching line along with the previous N lines of context when found

然后是中文译文:

比如,下面的代码在多行上面做简单的文本匹配, 并只返回在前N行中匹配成功的行

个人觉得后半句的翻译是错误的, 应该翻译为:

并返回匹配所在行的前N行

类似 grep 命令中的 -A 参数的含义

欢迎批评指正

10.11 包被引入两次

为什么 import 远程包之后输出了两次?

>>> import grok
I'm grok.__init__ 
I'm grok.__init__

1.2节的小问题。

在1.2节的讨论的第一个例子里列表与元祖的最后多一个,号
records = [
('foo', 1, 2),
('bar', 'hello'),
('foo', 3, 4),
]

第八章的两处错误

8.6章节中

import math
    class Circle:
        def __init__(self, radius):
            self.radius = radius

        @property
        def area(self):
            return math.pi * self.radius ** 2

        @property
        def diameter(self):
            return self.radius ** 2     这里有错误,直径不应该是半径的2次方,并且英文原版书籍中没有这个方法

        @property
        def perimeter(self):
            return 2 * math.pi * self.radius

8.8章节中
102行,因此,但你扩展一个property的时候,你需要先确定你是否要重新定义所有的方法还是说只修改其中某一个。中但应改成当

class SubPerson(Person):
    @Person.getter  这里有错误,见下方说明
    def name(self):
        print('Getting name')
        return super().name

138行翻译源码中 @Person.getter 不对,应改成@Person.name.getter,英文原版书籍中的这段代码也是有错误的,请确认一下吧

1.18节出现缩进错误

def compute_cost(records):
total = 0.0
for rec in records:
total += rec[1] * rec[2]
return total

这里,是不是粘贴时候没弄好。。。

代码中的注释需要翻译吗?

import os
import fnmatch
import gzip
import bz2
import re

def gen_find(filepat, top):
    '''
    Find all filenames in a directory tree that match a shell wildcard pattern
    '''
    for path, dirlist, filelist in os.walk(top):
        for name in fnmatch.filter(filelist, filepat):
            yield os.path.join(path,name)

def gen_opener(filenames):
    '''
    Open a sequence of filenames one at a time producing a file object.
    The file is closed immediately when proceeding to the next iteration.
    '''
    for filename in filenames:
        if filename.endswith('.gz'):
            f = gzip.open(filename, 'rt')
        elif filename.endswith('.bz2'):
            f = bz2.open(filename, 'rt')
        else:
            f = open(filename, 'rt')
        yield f
        f.close()

def gen_concatenate(iterators):
    '''
    Chain a sequence of iterators together into a single sequence.
    '''
    for it in iterators:
        yield from it

def gen_grep(pattern, lines):
    '''
    Look for a regex pattern in a sequence of lines
    '''
    pat = re.compile(pattern)
    for line in lines:
        if pat.search(line):
            yield line

Develop branch?

主页上

It's NOT recommended to submit a pull request directly to master branch. develop branch is more appropriate

但是repo好像没有develop branch?

笔误指正

感谢译者翻译。。
"解决方案" 里面的search函数

for li in lines:
    if pattern in li:
        yield li, previous_lines
    previous_lines.append(line)

previous_lines.append(line)
变量应该为li, 误写为line, 请修正 :)

7.3的小问题

尽管注解的使用方法可能有很多种,但是它们的主要用途还是文档。 因为python并没有类型声明,通常来讲仅仅通过阅读源码很难知道应该传递什么样的参数给这个函数。 这时候使用注解就能给程序员更多的提示,让他们可以争取的使用函数。

应该是“正确”使用函数

2.14节有一处代码缩进有错误

def combine(source, maxsize):
    parts = []
    size = 0
    for part in source:
        parts.append(part)
        size += len(part)
        if size > maxsize:
            yield ''.join(parts)
            parts = []
            size = 0
        yield ''.join(parts)   # 这一行应该是与for循环对齐吧,我理解应该是把没在for循环里yield输出的parts最后一起yield输出出去

# 结合文件操作
with open('filename', 'w') as f:
    for part in combine(sample(), 32768):
        f.write(part)

Three undefined names

flake8 testing of https://github.com/yidao620c/python3-cookbook on Python 3.6.3

$ flake8 . --count --select=E901,E999,F821,F822,F823 --show-source --statistics

./cookbook/c04/p16_iterate_while.py:11:11: F821 undefined name 'data'
    print(data)
          ^

./cookbook/c12/p01_start_stop_thread.py:51:9: F821 undefined name 'sock'
        sock.settimeout(5)   # set timeout period
        ^

./cookbook/c12/p01_start_stop_thread.py:55:24: F821 undefined name 'sock'
                data = sock.recv(8192)
                       ^

中文标点和中英文空格问题

我看了一下,文中有很多地方还用了英文标点,而且中英文之间没有空格。
在我看来,肯定是应该用中文标点的,所以我看了一下,并把第一章的标点改过来了,后面我再看看修改一下后面的部分。
还有就是中英文之间是应该有一个空格的,不知道大家怎么看?

存在版权问题

你把别人的书上传上来,又进行翻译,甚至希望收到捐款,这样不合适吧

关于1.8节的列子 有些不理解

首先很感谢作者提供的翻译教程。
这里有个问题不太明白,希望能够解答一下。

prices = {
'ACME': 45.23,
'AAPL': 612.78,
'IBM': 205.55,
'HPQ': 37.20,
'FB': 10.75
}
min(zip(prices.values(), prices.keys()))
price 是一个字典 对于一个无序的字典
这里的prices.values() 和 prices.keys()
怎么让它们的 key-values对应上的?

12.1 启动与停止线程代码缩进出现错误

错误的部分

# Code to execute in an independent thread
import time
def countdown(n):
    while n > 0:
    print('T-minus', n)
    n -= 1
    time.sleep(5)

# Create and launch a thread
from threading import Thread
t = Thread(target=countdown, args=(10,))
t.start()

while n>0:后部分的缩进出现问题

存在版权问题

存在版权问题,在没有作者授权的情况下,这种有版权争议的东西最好不要放到开源社区吧,自己半夜撸一撸还是可以的。

错别字

1.17节中,应该是dict,这里写成了dcit。

但是,字典推导方式表意更清晰,并且实际上也会运行的更快些 (在这个例子中,实际测试几乎比 dcit() 函数方式快整整一倍)。

2.5 小节的翻译问题

英文原文:

Problem

You want to search for and replace a text pattern in a string.

我觉得应该把中文翻译的
你想在字符串中搜索和匹配指定的文本模式 改为 -> 你想在字符串中搜索指定的文本模式并替换

你好,1.3节例子代码有问题

源码:
def search(lines, pattern, history=5):
previous_lines = deque(maxlen=history)
for li in lines:
if pattern in li:
yield li, previous_lines
previous_lines.append(li)

5.2小结:文件使用`rt`模式打开,但是却尝试写入文本

原文:

print() 函数中指定 file 关键字参数,像下面这样:

with open('somefile.txt', 'rt') as f:
     print('Hello World!', file=f)

我不知道这里为什么会是这样,难道不应该使用wa模式打开吗?

附:表示尝试后确实无法写入,而且f.writable()结果为False

网页版有些地方无法显示

举个例子:

第六章第一节, "类似下面这样:" 下面没东西

theworld_2016-03-31_20-23-04

第六章第四节也这样,可能还有

原因是 这里的高亮是 code-block:: 如果是 code-block:: text 就没问题,不过也许是别的语法,我对rst不熟悉

错别字

附录里有几个错别字,好像现在还没有更正。

我之前提交过一个PR,不过似乎文件有冲突。

版主有空改一下呗。

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.