进阶代码

Buffer

// 1. alloc
let buf = Buffer.alloc(10);
console.log(buf);

// 2. alloucUnsafe
let buf_2 = Buffer.allocUnsafe(10000);
console.log(buf_2);

// 3. from
let buf_3 = Buffer.from('hello');
// 转二进制
console.log(buf[0].toString(2));
console.log(buf_3);

let buf_4 = Buffer.from([105, 108, 111, 118, 101, 121, 111, 117]);
console.log(buf_4);
// buffer与字符串的转换
console.log(buf_4.toString());

文件的读取操作

文件编码概念

编码技术即: 翻译的规则,记录了如何将内容翻译成二进制,以及如何将二进制翻译回可识别的内容。

计算机中可用编码:

  • UTF-8

  • GBK

  • Big5

不同的编码,将内容翻译成二进制也是不同的。

UTF-8是目前全球通用的编码格式

除非由特殊需求,否则,一律以UTF-8格式进行文件编码即可。

# 读取全部内容,通过字符串count方法统计itheima单词数量
with open("word.txt", "r", encoding="utf-8") as f:
    content = f.read()
    count = content.count("itheima")
    print(f"itheima在文件中出现了: {count}次")

json

"""
演示JSON数据和Python字典的相互转换
"""
import json


# 准备列表,列表内每一个元素都是字典, 将其转换位JSON
data = [{'name': '张大山', 'age': 11}, {'name': "王大锤", 'age': 13}, {'name': '赵小虎', 'age': 16}]
# ensure_ascii默认为True, 中文会显示unicode的形式,例如"张大山"显示为"\u5f20\u5927\u5c71"
json_str = json.dumps(data, ensure_ascii=False)
print(type(json_str))
print(json_str)

# 准备字典,将字典转换位JSON
d = {'name': '周杰轮', 'addr': '台北'}
json_str = json.dumps(d, ensure_ascii=False)
print(type(json_str))
print(json_str)

# 将JSON字符串列表转换为Python数据类型[{k: v, k: v}, {k:v, k:v}]
s = '[{"name": "张大山", "age": 11}, {"name": "王大锤", "age": 13}, {"name": "赵小虎", "age": 16}]'
l = json.loads(s)
print(type(l))
print(l)

# 将JSON字符串转换为Python数据类型{k:v,k:v}
s = '{"name": "周杰轮", "addr": "台北"}'
d = json.loads(s)
print(type(d))
print(d)

高阶函数和可调用对象上的操作

缓存树形(cached_property)

https://docs.python.org/zh-cn/3.10/library/functools.html#functools.cached_property

使用案例: v4.2.X django.core.cache.backends.redis.RedisCache

懒加载redis连接

class RedisCache(BaseCache):
    def __init__(self, server, params):
        super().__init__(params)
        if isinstance(server, str):
            self._servers = re.split("[;,]", server)
        else:
            self._servers = server

        self._class = RedisCacheClient
        self._options = params.get("OPTIONS", {})

    @cached_property
    def _cache(self):
        # 在第一次使用时才实例化redis对象,且缓存下来
        return self._class(self._servers, **self._options)

多线程

todo

socket

todo

正则表达式

todo

递归

todo