Python 字典排序

Sort a dictionary by value
依据字典的值进行排序

newDict = {k: v for k, v in sorted(x.items(), key=lambda item: item[1])}
import operator


# 示例字典
d = {'a': 3, 'e': 4, 'b': 2, 'c': 5, 'd': 1}


# 按 key 排序
def dict_sort_by_key(d: dict):
    sorted_d = sorted(d.items(), key=operator.itemgetter(0))
    return dict(sorted_d)

# 按 value 排序
def dict_sort_by_val(d: dict):
    # sorted_dic = dict(sorted(d.items(), key=operator.itemgetter(1)))
	
	sorted_keys=sorted(dict1, key=dict1.get)
	for k in sorted_keys:
		sorted_dic[k]=d[k]
	
    return sorted_dic


print(dict_sort_by_key(d))
# {'a': 3, 'b': 2, 'c': 5, 'd': 1, 'e': 4}

print(dict_sort_by_val(d))
# {'d': 1, 'b': 2, 'a': 3, 'e': 4, 'c': 5}

Python 计算 MD5 散列值

def get_md5_string(content)->str:
    """
    - content: bytes or string
    """
    m = hashlib.md5()
    if type(content) == bytes:
        m.update(content)
    elif type(content) == str:
        m.update(content.encode())
    else:
        return None
    return m.hexdigest()

AWS 在本地配置AWS资源访问授权

如果本地安装了 AWS CLI 可以直接使用 aws 命令进行配置:
aws configure

或者,可以手动创建证书文件,文件默认位置是 ~/.aws/credentials

文件内容:

[default]
aws_access_key_id=YOUR_ACCESS_KEY
aws_secret_access_key=YOUR_SECRET_KEY

如果要设置默认地区(Regoin),示例:

BeautifulSoup 获取DOM元素的文本

举例:

from bs4 import BeautifulSoup

html="""<div>Hello<br>
<br> World!</div>""" # 示例HTML

soup = BeautifulSoup(html, 'html.parser')
elem = soup.select_one('div')

纯文本。
旧版。只是去除了 HTML tag,留下了空白字符,包括换行符。
新版。去除了 HTML tag 、换行、多余的空白字符。

print(elem.get_text())
# 输出:
'''
Hello
 World!
'''

elem.stripped_strings 以迭代方式返回每个HTML tag 间的文本,但会过滤掉多余的空白字符。

Homebrew update 失败,报错 homebrew-core is a shallow clone

发生环境:macOS V11.1 (Big Sur)

发生的问题:brew update 时报错,

Error: 
  homebrew-core is a shallow clone.
  homebrew-cask is a shallow clone.
To `brew update`, first run:
  git -C /usr/local/Homebrew/Library/Taps/homebrew/homebrew-core fetch --unshallow
  git -C /usr/local/Homebrew/Library/Taps/homebrew/homebrew-cask fetch --unshallow
This restriction has been made on GitHub's request because updating shallow
clones is an extremely expensive operation due to the tree layout and traffic of
Homebrew/homebrew-core and Homebrew/homebrew-cask. We don't do this for you
automatically to avoid repeatedly performing an expensive unshallow operation in
CI systems (which should instead be fixed to not use shallow clones). Sorry for
the inconvenience!
...

按照提示执行git -C /usr/local/Homebrew/Library/Taps/homebrew/homebrew-core fetch --unshallow,而往往等待很久后,还总是失败。
报错内容类似:
fatal: unable to access 'https://github.com/Homebrew/homebrew-core.git/': transfer closed with outstanding read data remaining