Study Plan For Python - Part4

格式化输出

1.reprlib 模块

提供了一个定制化版本的 repr() 函数,用于缩略显示大型或深层嵌套的容器对象

import reprlib
reprlib.repr(set('fantabulouslywonderificentamazingness')) # 可迭代对象,输出 "{'a', 'b', 'c', 'd', 'e', 'f', ...}"

2.pprint 模块

提供了更加复杂的打印控制,其输出的内置对象和用户自定义对象能够被解释器直接读取

具有美化输出机制

import pprint
t = [[[['black', 'pink'], 'white', ['green', 'red']], [['magenta',
    'yellow'], 'blue']]]

pprint.pprint(t, width=40)

3.textwrap 模块

格式化文本段落,以适应给定的屏幕宽度

import textwrap
doc = """The splitlines() method is just like split('\n') except that it returns a list of strings instead of a list of substrings based on a specific delimiter. It separates a string into lines based on the actual line breaks in the text."""

print(textwrap.fill(doc, width=40))

4.locale 模块

处理与特定地域文化相关的数据格式

import locale
locale.setlocale(locale.LC_ALL, 'English_United States.1252')

conv = locale.localeconv()          # 获取当前地域的文化惯例映射
x = 1234567.8
locale.format_string("%d", x, grouping=True)

locale.format_string("%s%.*f", (conv['currency_symbol'],
                     conv['frac_digits'], x), grouping=True)

模板

1.string 模块

提供了一个通用的 Template 类,允许用户在不更改应用逻辑的情况下定制自己的应用

格式化操作通过占位符实现,$$ 将被转义成单个字符 $

from string import Template

t = Template('${city}市民为$organization捐赠了$$100。')
t.substitute(city='广东', organization='希望工程')
t.safe_substitute(organization='希望工程') # 如果数据缺失,保留占位符原样

# 对一组照片文件进行批量重命名
import time, os.path
photofiles = ['img_1.jpg', 'img_2.jpg', 'img_3.jpg']
class BatchRename(Template):
    delimiter = '%' # 自定义分隔符

fmt = input('Enter rename style (%d-date %n-seqnum %f-format):  ')

t = BatchRename(fmt)
date = time.strftime('%d%b%y')
for i, filename in enumerate(photofiles):
    base, ext = os.path.splitext(filename)
    newname = t.substitute(d=date, n=i, f=ext)
    print('{0} ---> {1}'.format(filename, newname))

使用二进制数据记录格式

1.struct 模块

处理不定长度的二进制记录格式

# 不便用zipfile模块。读取一个ZIP文件,并解析其中的前三个文件头信息
import struct

with open('Archive.zip', 'rb') as f: # 只读,二进制
    data = f.read()

start = 0
for i in range(3):                      
    start += 14 # 将当前位置向后移动 14 个字节,跳过一些固定的字节以到达文件头的起始位置
    fields = struct.unpack('<IIIHH', data[start:start+16]) # 三个无符号整数和两个无符号短整数
    crc32, comp_size, uncomp_size, filenamesize, extra_size = fields

    start += 16 # 将当前位置再向后移动 16 个字节
    filename = data[start:start+filenamesize] # 对应ZIP文件中当前文件的文件名
    start += filenamesize
    extra = data[start:start+extra_size] # 额外数据
    print(filename, hex(crc32), comp_size, uncomp_size) # 文件名、CRC32 值的十六进制表示、压缩后大小和未压缩大小

    start += extra_size + comp_size     

多线程

1.threading 模块

# 一个自定义的线程类AsyncZip,用于在后台异步地将一个文件压缩为 ZIP 文件
import threading, zipfile

class AsyncZip(threading.Thread):
    def __init__(self, infile, outfile):
        threading.Thread.__init__(self)
        self.infile = infile
        self.outfile = outfile

    def run(self):
        f = zipfile.ZipFile(self.outfile, 'w', zipfile.ZIP_DEFLATED)
        f.write(self.infile)
        f.close()
        print('Background zip has completed.')

background = AsyncZip('data.txt', 'archive.zip')
background.start()
print('The main program is proceeding in the foreground.')

background.join()    
print('The main program has waited until background was finished.')

日志记录

1.logging 模块

提供日志记录系统

import logging # 级别:debug > info > warning > error > critical
logging.debug('Debugging information')
logging.info('Informational message')
logging.warning('Warning:config file %s not found', 'server.conf')
logging.error('Error occurred')
logging.critical('Critical error -- shutting down') # 严重错误

弱引用

1.weakref 模块

提供了对弱引用的支持

import weakref, gc
class A:
    def __init__(self, value):
        self.value = value
    def __repr__(self):
        return str(self.value)

a = A(10)                  
d = weakref.WeakValueDictionary() # 其中的值是弱引用
d['primary'] = a            # 不创建a的额外强引用,而是存储弱引用
d['primary']                

del a                       
gc.collect()                

d['primary']                # 仅被弱引用时,这个对象可以被垃圾回收   

用于操作列表的工具

1.array 模块

from array import array # array,只能存储类型一致的数据且存储密度更高
a = array('H', [3000, 10, 600, 3333333]) 
sum(a)

a[1:3]

2.collections 模块

from collections import deque # deque,高效的两端插入和删除操作
d = deque(["a", "b", "c"]) # 双端队列
d.append("d")
print("Handling", d.popleft())

# 广度优先搜索算法
from collections import deque

graph = { # 字典
    'A': ['B', 'C'],
    'B': ['D', 'E'],
    'C': ['F'],
    'D': [],
    'E': ['F'],
    'F': []
}

def bfs(graph, start):
    visited = set()
    queue = deque([start])
    visited.add(start)
    while queue:
        node = queue.popleft()
        print(node)
        for neighbor in graph[node]:
            if neighbor not in visited:
                queue.append(neighbor)
                visited.add(neighbor)

3.bisect 模块

有序列表中快速插入

import bisect
scores = [(1, 'a'), (2, 'b'), (4, 'c'), (5, 'd')]
bisect.insort(scores, (3, 'e'))
scores # 输出 [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'e'), (5, 'd')]

4.heapq 模块

提供了堆数据结构的实现

from heapq import heapify, heappop, heappush
data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
heapify(data)                      # 转换为堆,最小的元素位于堆的根节点
heappush(data, -5)                 
[heappop(data) for i in range(3)] # 列表

十进制浮点运算

1.decimal 模块

用于十进制浮点运算

Decimal('1.00') % Decimal('.10') # Decimal('0.00')
1.00 % 0.10 # 0.09999999999999995
sum([Decimal('0.1')]*10) == Decimal('1.0') # True
0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 == 1.0 # False     0.1 的二进制表示为无限循环小数
That's great! OpenCV (Open Source Computer Vision) is a powerful computer vision library that you can use to analyze and manipulate images and videos. Here are some steps you can follow to get started with studying OpenCV in Python: 1. Install OpenCV: You can install OpenCV in Python using pip. Open your terminal and type `pip install opencv-python` to install it. 2. Learn the basics of Python: Before you start working with OpenCV, you should have a basic understanding of Python programming. You can start with learning Python syntax, data types, control structures, functions, and classes. 3. Learn the basics of computer vision: Computer vision is a broad field that covers a wide range of topics, including image processing, object detection, face recognition, and machine learning. You can start by learning the basics of image processing, such as image filtering, thresholding, and edge detection. 4. Read the OpenCV documentation: The OpenCV documentation is an excellent resource for learning how to use the library. You can find tutorials, examples, and documentation on the OpenCV website. 5. Practice coding: The best way to learn OpenCV is to practice coding. Start with simple image processing tasks, such as reading and displaying images, and then move on to more advanced tasks like object detection and tracking. 6. Join OpenCV communities: Joining OpenCV communities can help you learn from other developers and get answers to your questions. You can join the OpenCV forum, Stack Overflow, and other online communities. With these steps, you can start your journey to becoming an OpenCV expert in Python. Good luck!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

五月的风与火

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值