Пример #1
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import time, os, sys

BATCHPATH = os.path.dirname(os.path.dirname(os.path.abspath(os.path.realpath(__file__))))
sys.path.insert(0, BATCHPATH)

from lib.base import gettime, info, warn, error

from unicodedata import name

if __name__ =='__main__':
    s = {chr(i) for i in range(32, 256) if 'SIGN' in name(chr(i),'')}
    info("s: %s" %(s))
Пример #2
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import time, os, sys

BATCHPATH = os.path.dirname(
    os.path.dirname(os.path.abspath(os.path.realpath(__file__))))
sys.path.insert(0, BATCHPATH)

from lib.base import gettime, info, warn, error

if __name__ == '__main__':
    s = 'café'

    # ❶ 'café' 字符串有 4 个 Unicode 字符
    info("len(s): %s" % (len(s)))

    # ❷ 使用 UTF-8 把 str 对象编码成 bytes 对象
    b = s.encode('utf8')

    # ❸ bytes 字面量以 b 开头
    info("b: %s" % (b))

    # ❹ 字节序列 b 有 5 个字节(在 UTF-8 中, “é”的码位编码成两个字节)
    info("len(b): %s" % (len(b)))

    # ❺ 使用 UTF-8 把 bytes 对象解码成 str 对象
    info("b.decode('utf8'): %s" % (b.decode('utf8')))

    # ❶ bytes 对象可以从 str 对象使用给定的编码构建
    cafe = bytes('café', encoding='utf_8')
Пример #3
0
    DIAL_CODES = [
        (86, 'China'),
        (91, 'India'),
        (1, 'United States'),
        (62, 'Indonesia'),
        (55, 'Brazil'),
        (92, 'Pakistan'),
        (880, 'Bangladesh'),
        (234, 'Nigeria'),
        (7, 'Russia'),
        (81, 'Japan'),
    ]

    # ❷ 这里把配好对的数据左右换了下, 国家名是键, 区域码是值
    country_code = {country: code for code, country in DIAL_CODES}
    info("country_code: %s" % (country_code))

    # ❸ 跟上面相反, 用区域码作为键, 国家名称转换为大写, 并且过滤掉区域码大于或等于 66 的地区
    country_code2 = {
        code: country.upper()
        for country, code in country_code.items() if code < 66
    }
    info("country_code2: %s" % (country_code2))

    country_code3 = {
        code: country.upper()
        for country, code in country_code.items()
        if code < 66 and country[0] in "IU"
    }
    info("country_code3: %s" % (country_code3))
Пример #4
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import time, os, sys

BATCHPATH = os.path.dirname(
    os.path.dirname(os.path.abspath(os.path.realpath(__file__))))
sys.path.insert(0, BATCHPATH)

from lib.base import gettime, info, warn, error

if __name__ == '__main__':
    a = dict(one=1, two=2, three=3)
    b = {'one': 1, 'two': 2, 'three': 3}
    c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
    d = dict([('two', 2), ('one', 1), ('three', 3)])
    e = dict({'three': 3, 'one': 1, 'two': 2})

    info("(a == b == c == d == e): %s" % (a == b == c == d == e))
Пример #5
0
import time, os, sys

BATCHPATH = os.path.dirname(
    os.path.dirname(os.path.abspath(os.path.realpath(__file__))))
sys.path.insert(0, BATCHPATH)

from lib.base import gettime, info, warn, error
import re

# 用一行就解决了获取和更新单词的出现情况列
# 表, 当然跟示例 3-2 不一样的是, 这里用到了 dict.setdefault
if __name__ == '__main__':
    if len(sys.argv) > 1:
        WORD_RE = re.compile(r'\w+')
        index = {}
        with open(sys.argv[1], encoding='utf-8') as fp:
            for line_no, line in enumerate(fp, 1):
                for match in WORD_RE.finditer(line):
                    word = match.group()
                    column_no = match.start() + 1
                    location = (line_no, column_no)
                    # ➊ 获取单词的出现情况列表, 如果单词不存在, 把单词和一个空列表
                    # 放进映射, 然后返回这个空列表, 这样就能在不进行第二次查找的情况
                    # 下更新列表了
                    index.setdefault(word, []).append(location)

        # 以字母顺序打印出结果
        for word in sorted(index, key=str.upper):
            info(word, index[word])
Пример #6
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import time, os, sys

BATCHPATH = os.path.dirname(
    os.path.dirname(os.path.abspath(os.path.realpath(__file__))))
sys.path.insert(0, BATCHPATH)

from lib.base import gettime, info, warn, error

import collections
import builtins

if __name__ == '__main__':
    pylookup = collections.ChainMap(locals(), globals(), vars(builtins))
    info("pylookup: %s" % (pylookup))
Пример #7
0
BATCHPATH = os.path.dirname(os.path.dirname(os.path.abspath(os.path.realpath(__file__))))
sys.path.insert(0, BATCHPATH)

from lib.base import gettime, info, warn, error

# ❶ 从 Python 3.0 起, reduce 不再是内置函数了
from functools import reduce

# ❷ 导入 add, 以免创建一个专求两数之和的函数
from operator import add


# 计算阶乘列表: map 和 filter 与列表推导比较
if __name__ =='__main__':
    # ❸ 计算 0~99 之和。
    info("reduce(add, range(100)): %s" %(reduce(add, range(100))))

    # ❹ 使用 sum 做相同的求和; 无需导入或创建求和函数
    info("sum(range(100)): %s" %(sum(range(100))))


    a = ["", 0, 1, "abc"]
    b = ["abc", 1, [1], {1}]
    c = ["", 0, [], {}]

    print("a: %s" %(a))
    print("b: %s" %(b))
    print("c: %s" %(c))

    print("any(a): %s" %(any(a)))
    print("any(b): %s" %(any(b)))
Пример #8
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import time, os, sys

BATCHPATH = os.path.dirname(os.path.dirname(os.path.abspath(os.path.realpath(__file__))))
sys.path.insert(0, BATCHPATH)

from lib.base import gettime, info, warn, error

from types import MappingProxyType


if __name__ =='__main__':
    d = {1:'A'}
    d_proxy = MappingProxyType(d)
    info("d_proxy: %s" %(d_proxy))
    info("d_proxy[1]: %s" %(d_proxy[1]))

    try:
        d_proxy[2] = 'x'
    except Exception as err:
        error("exception: %s" %(err))

    d[2] = 'B'
    info("d_proxy: %s" %(d_proxy))
    info("d_proxy[2]: %s" %(d_proxy[2]))

Пример #9
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import time, os, sys

BATCHPATH = os.path.dirname(
    os.path.dirname(os.path.abspath(os.path.realpath(__file__))))
sys.path.insert(0, BATCHPATH)

from lib.base import gettime, info, warn, error

if __name__ == '__main__':
    l = ['spam', 'spam', 'eggs', 'spam']

    s = set(l)
    info("s: %s" % (s))

    l2 = list(s)
    info("l2: %s" % (l2))

    s1 = set([a for a in "abcdef"])
    s2 = set([a for a in "defgh"])

    info("s1: %s" % (s1))
    info("s2: %s" % (s2))

    # info("s1+s2: %s" %(s1+s2))
    info("s1|s2: %s" % (s1 | s2))

    info("s1&s2: %s" % (s1 & s2))
    info("s1-s2: %s" % (s1 - s2))
Пример #10
0
import time, os, sys

BATCHPATH = os.path.dirname(os.path.dirname(os.path.abspath(os.path.realpath(__file__))))
sys.path.insert(0, BATCHPATH)

from lib.base import gettime, info, warn, error


def factorial(n):
    '''returns n!'''
    return 1 if n < 2 else n * factorial(n-1)

# 创建并测试一个函数, 然后读取它的 __doc__ 属性, 再检查它的类型
if __name__ =='__main__':
    info("factorial(42): %s" %(factorial(42)))

    info("type(factorial): %s" %(type(factorial)))

    # 文档
    info("factorial.__doc__: %s" %(factorial.__doc__))

    # 别名
    fact = factorial
    info("fact(5): %s" %(fact(5)))

    # 入参
    info("map(factorial, range(11)): %s" %(map(factorial, range(11))))
    info("list(map(fact, range(11))): %s" %(list(map(fact, range(11)))))

    l = range(11)
Пример #11
0
    # 世界人口数量前10位国家的电话区号
    DIAL_CODES = [
        (86, 'China'),
        (91, 'India'),
        (1, 'United States'),
        (62, 'Indonesia'),
        (55, 'Brazil'),
        (92, 'Pakistan'),
        (880, 'Bangladesh'),
        (234, 'Nigeria'),
        (7, 'Russia'),
        (81, 'Japan'),
    ]

    # ➊ 创建 d1 的时候, 数据元组的顺序是按照国家的人口排名来决定的。
    d1 = dict(DIAL_CODES)
    info('d1: %s' % d1.keys())

    # ➋ 创建 d2 的时候, 数据元组的顺序是按照国家的电话区号来决定的
    d2 = dict(sorted(DIAL_CODES))
    info('d2: %s' % d2.keys())

    # ➌ 创建 d3 的时候, 数据元组的顺序是按照国家名字的英文拼写来决定的
    d3 = dict(sorted(DIAL_CODES, key=lambda x: x[1]))
    info('d3: %s' % d3.keys())

    # ➍ 这些字典是相等的, 因为它们所包含的数据是一样的。 示例 3-18 里是上面例子的输出。
    assert (d1 == d2 and d2 == d3)

    # 往字典里添加新键可能会改变已有键的顺序
Пример #12
0
async def hello():
    asyncio.sleep(1)
    info("hello world")
Пример #13
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import time, os, sys
import asyncio

BATCHPATH = os.path.dirname(os.path.dirname(os.path.abspath(os.path.realpath(__file__))))
sys.path.insert(0, BATCHPATH)

from lib.base import gettime, info, warn, error

# 定义异步函数
async def hello():
    asyncio.sleep(1)
    info("hello world")

def run():
    for i in range(5):
        asyncio.get_event_loop().run_until_complete(hello())


if __name__ =='__main__':
    info("go")
    run()
    info("done")


Пример #14
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import time, os, sys

BATCHPATH = os.path.dirname(
    os.path.dirname(os.path.abspath(os.path.realpath(__file__))))
sys.path.insert(0, BATCHPATH)

from lib.base import gettime, info, warn, error

import collections

if __name__ == '__main__':
    ct = collections.Counter('abracadabra')
    info("ct: %s" % (ct))

    ct.update('aaaaazzz')
    info("ct: %s" % (ct))
Пример #15
0
import time, os, sys

BATCHPATH = os.path.dirname(
    os.path.dirname(os.path.abspath(os.path.realpath(__file__))))
sys.path.insert(0, BATCHPATH)

from lib.base import gettime, info, warn, error
import struct

if __name__ == '__main__':
    # ❶ 结构体的格式: < 是小字节序, 3s3s 是两个 3 字节序列, HH 是两个16 位二进制整数
    fmt = '<3s3sHH'
    with open('o.gif', 'rb') as fp:
        # ❷ 使用内存中的文件内容创建一个 memoryview 对象
        img = memoryview(fp.read())

    # ❸ 然后使用它的切片再创建一个 memoryview 对象; 这里不会复制字节序列
    header = img[:10]

    # ❹ 转换成字节序列, 这只是为了显示; 这里复制了 10 字节
    info("bytes(header): %s" % (bytes(header)))

    # ❺ 拆包 memoryview 对象, 得到一个元组, 包含类型、 版本、 宽度和高度
    un = struct.unpack(fmt, header)
    info("un: %s" % (un))

    # ❻ 删除引用, 释放 memoryview 实例所占的内存
    del header
    del img
Пример #16
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import time, os, sys

BATCHPATH = os.path.dirname(
    os.path.dirname(os.path.abspath(os.path.realpath(__file__))))
sys.path.insert(0, BATCHPATH)

from lib.base import gettime, info, warn, error

if __name__ == '__main__':
    tt = (1, 2, (30, 40))
    info("hash(tt): {0}".format(hash(tt)))

    tl = (1, 2, [30, 40])
    try:
        info("hash(tl): {0}".format(hash(tl)))
    except Exception as err:
        warn("throw: {0}".format(err))

    tf = (1, 2, frozenset([30, 40]))
    info("hash(tf): {0}".format(hash(tf)))