0. xlwings 简介

xlwings 提供了四种用法:

  • xlwings (Open Source), 本地 python模块、excel插件,代码在本地,运行在本地
  • xlwings PRO, 商业版,收费
  • xlwings Lite, 代码内置在excel文件中、运行在云端(代码公开)
  • xlwings Server, 商业版,收费

1. xlwings (Open Source) 本地版,在 excel 中使用自定义 python 函数

1.1 excel 启用宏

文件 -> 选项 -> 信任中心 -> 信任中心设置 ->
宏设置 -> 勾选 启用VBA宏信任对VBA工程对象模型的访问

1.2 安装 xlwings (Open Source)

1
2
3
4
5
6

pip install xlwings
xlwings addin install

# xlwings addin remove
# pip uninstall xlwings

1.3 快速使用

1
2
3
4
xlwings config create --force
# .xlwings\xlwings.conf

xlwings quickstart xlwings_test

xlwings quickstart 命令会自动建立一个文件夹,内部有两个文件:

  • xlwings_test.xlsm
  • xlwings_test.py
阅读全文 »

1. pyproject.toml 说明

pyproject.toml 是目前官方推荐的打包方式。

官网写的比较抽象。
这里记录下一个简单的使用方法。

2. 包的文件夹结构

建议的包文件结构如下,假设要创建一个名为snake的包:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
snake_proj
├──src/
└──snake/
├──__init__.py
├──AA.py
├──BB.py
└──snake_data/
├──xx.txt
└──yy.txt
├──tests/
└──snake/
├──.gitignore
├──LICENSE
├──pyproject.toml
└──README.md

3. 编写 pyproject.toml

阅读全文 »

一、openmc 面命令

https://docs.openmc.org/en/stable/pythonapi/generated/openmc.XPlane.html

method mcnp paras 参数说明 geometry
openmc.Plane 任意无限平面 a=1, b=0, c=0, d=0 系数 $Ax+By+Cz=D$
openmc.XPlane X无限平面 x0=0 与原点的距离 $x−x_0=0$
openmc.YPlane Y无限平面 y0=0 与原点的距离 $y−y_0=0$
openmc.ZPlane Z无限平面 z0=0 与原点的距离 $z−z_0​=0$
openmc.XCylinder X无限圆柱 y0=0, z0=0, r=1 圆柱中心y0,z0
圆柱半径r
$(y−y_0​)^2+(z−z_0​)^2=r^2$
openmc.YCylinder Y无限圆柱 x0=0, z0=0, r=1 圆柱中心x0,z0
圆柱半径r
$(x−x_0​)^2+(z−z_0​)^2=r^2$
openmc.ZCylinder Z无限圆柱 x0=0, y0=0, r=1 圆柱中心x0,y0
圆柱半径r
$(x−x_0​)^2+(y−y_0​)^2=r^2$
openmc.Sphere 球面 x0=0, y0=0, z0=0, r=1 球心 x0,y0,z0
球半径r
$(x−x_0)^2+(y−y_0)^2+(z−z_0)^2=r^2$
openmc.Cone 圆锥面
openmc.XCone x方向圆锥面 $(y−y_0)^2+(z−z_0)^2=r^2(x−x_0)^2$
openmc.YCone y方向圆锥面
openmc.ZCone z方向圆锥面
openmc.Quadric 二次曲面
openmc.XTorus x环面
openmc.YTorus y环面
openmc.ZTorus z环面

二、openmc 复合面命令 (mcnp macrobody)

https://docs.openmc.org/en/stable/pythonapi/model.html#composite-surfaces

method 复合面 mcnp paras
ConicalFrustum 圆锥台 TRC center_base 底面中心
axis 轴线方向
r1 底面半径
r2 顶面半径
CruciformPrism 多边形棱柱体 distances 距离
center=(0, 0) 中心
axis=”z” 轴线
CylinderSector 无限扇形柱体 r1 扇内半径
r2 扇外半径 theta1 起始角度
theta2 结束角度
center 中心轴坐标
axis 中心轴
HexagonalPrism 六边形柱体 edge_length=1 边长
orientation 方向
origin 原点
IsogonalOctagon 八边形柱体题 center 中心轴坐标
r1 半宽 r2 半宽
axis=”z” 轴线
OrthogonalBox 任意正交体 BOX v 顶点坐标
a1 边1向量
a2 边2向量
a3 边3向量
Polygon 闭合点路径形成的多边形 points 点集
basis 基
RectangularParallelepiped 平行于轴的长方体 RPP xmin xmax ymin ymax zmin zmax 坐标范围
RectangularPrism 四面围成的无限长方体 width 宽
height 高
axis 轴向
origin 原点
RightCircularCylinder 圆柱体 RCC center_base 底面中心
height 高度
radius 半径
axis 中心轴
Vessel 圆柱容器及椭圆封头 r 半径
p1 坐标
p2 坐标
h1 下封头高度
h2 上封头高度
center 中心轴坐标
axis 中心轴
XConeOneSided x方向圆锥
YConeOneSided y方向圆锥
ZConeOneSided z方向圆锥

numpy的保存

https://numpy.org/doc/stable/reference/generated/numpy.save.html

numpy保存数组比较简单。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 1. 保存单个数组
numpy.save(file, arr, allow_pickle=True)

# 2. 保存多个数组
numpy.savez(file, *args, allow_pickle=True, **kwds)

# 保存时如果不指定数组名字, 默认按照 arr_0, arr_1 编号
numpy.savez(file, a1, a2) # Arrays will be named: arr_0, arr_1 ...
# 保存时指定数组名字
numpy.savez(file, a1=a1, a2=a2) # Arrays will be named: a1, a2 ...

# 读取 npz
npzfile = np.load('file.npz')
print(npzfile.files)

a1, a2 = [npzfile[key] for key in npzfile.files]

# 3. 保存多个数组, 保存时进行数据压缩,用法与 numpy.savez() 一样
# 压缩率一般在 10 倍以上,相应牺牲的是读取、保存时间,时间消耗大概是同样的倍率。
numpy.savez_compressed(file, *args, allow_pickle=True, **kwds)

pandas的保存

https://pandas.pydata.org/docs/user_guide/io.html

pandas保存复杂得多,提供了非常多的格式,常见的:csv,xlsx,h5等。

Type Data Description Reader Writer
text CSV read_csv to_csv
text Fixed-Width Text File read_fwf NA
text JSON read_json to_json
text HTML read_html to_html
text LaTeX Styler.to_latex NA
text XML read_xml to_xml
text Local clipboard read_clipboard to_clipboard
binary MS Excel read_excel to_excel
binary OpenDocument read_excel NA
binary HDF5 Format read_hdf to_hdf
binary Feather Format read_feather to_feather
binary Parquet Format read_parquet to_parquet
binary ORC Format read_orc to_orc
binary Stata read_stata to_stata
binary SAS read_sas NA
binary SPSS read_spss NA
binary Python Pickle Format read_pickle to_pickle
SQL SQL read_sql to_sql
阅读全文 »

1
2
3
4
5
6
7
8
9
10
11
> mklink

创建符号链接。

MKLINK [[/D] | [/H] | [/J]] Link Target

/D 创建目录符号链接。默认为文件符号链接。
/H 创建硬链接而非符号链接。
/J 创建目录联接。
Link 指定新的符号链接名称。
Target 指定新链接引用的路径 (相对或绝对)。

例:创建wechat文件夹目录链接

将微信默认的接收文件夹 设置到 指定位置。

注意:命令执行需要左边文件夹不存在,可先将微信退出、默认文件夹重命名为 file1、然后执行命令,再将 file1 中全部文件移至 file 里。

1
2
3
4
5
# mklink /J [微信默认文件夹路径] [自定义的文件夹路径]
mklink /J xxxx\wechat\xwechat_files\wxid_123456789_1234\msg\file yyyy\weixin_file

# output
# 为 xxxx\wechat\xwechat_files\wxid_123456789_1234\msg\file <<===>> yyyy\weixin_file 创建的联接

烟波金陵 缥缈江湖
车走马急 你追我逐
尽己所能 敬我弗如
梦遥路远 终有归途

二零二五元旦于红杏楼

gif

pillow

1
2
3
4
5
6
7
8
9
from PIL import Image
import glob

pngs = glob.glob('temp_png/*.png')
# print(pngs)

frames = [Image.open(png) for png in pngs]

frames[0].save('z.gif', format='GIF', append_images=frames[1:], save_all=True, duration=100, loop=0)

mp4

opencv-python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import glob
import cv2

pngs = glob.glob('temp_png/*.png')
# print(pngs)

frames = [cv2.imread(png) for png in pngs]

h, w, l = frames[0].shape
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
video = cv2.VideoWriter(f'{pl}.mp4', fourcc, 15, (w, h))
for f in frames:
video.write(f)

cv2.destroyAllWindows()
video.release()

用 pandoc 将 latex 转换为 word 文档

ref: https://www.cnblogs.com/jiankychen/p/pandoc.html

1
2
3
4
5
6
7
8
9
10
11
pandoc paper.tex |
--number-sections |
--filter pandoc-crossref |
-t docx+native_numbering |
-M tableEqns -M autoEqnLabels |
--bibliography ref.bib |
--citeproc --csl ieee-wireless-communications-letters.csl |
-M reference-section-title=Reference |
--reference-doc template.docx |
-o output.docx

阅读全文 »

1. blender 运动基础: 平移、旋转

创建一个立方体,按照动作设定坐标后新建关键帧,就可以了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# give Python access to Blender's functionality
import bpy
# extend Python's math functionality
import math

# add a cube into the scene
bpy.ops.mesh.primitive_cube_add()
# get a reference to the currently active object
cube = bpy.context.active_object

# insert keyframe at frame one
cube.keyframe_insert("rotation_euler", frame=1)
# change the rotation of the cube around z-axis
cube.rotation_euler.z = math.radians(360)

# insert keyframe at the last frame
cube.keyframe_insert("rotation_euler", frame=90)

# change the location of the cube on the z-axis
cube.location.z = 0
cube.keyframe_insert("location", frame=100)
cube.location.z = 5
cube.keyframe_insert("location", frame=150)

阅读全文 »

Blender mesh 创建点线面 uOQ-CPcaqMo AxazJi3x6js

任务:创建一个半径为2圆环,圆环上均布32个点,显示为点或者线。

1. 点

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# give Python access to Blender's functionality
import bpy
# extend Python's math functionality
import math
# extend Python's print functionality
import pprint

# initialize paramaters
vert_count = 32 # show with 16 and 64
angle_step = math.tau / vert_count
radius = 2

# create a list of vert coordinates
vert_coordinates = list()

# repeat code in a loop
for i in range(vert_count):

# calculate current current_angle
current_angle = angle_step * i

# calculate coordinate
x = radius * math.cos(current_angle)
y = radius * math.sin(current_angle)

# visualize what we are doing
bpy.ops.mesh.primitive_ico_sphere_add(radius=0.05, location=(x, y, 0))

# add current coordinate to list
vert_coordinates.append((x, y, 0))

pprint.pprint(vert_coordinates)
阅读全文 »

Blender Python 配置 (on Windows) YUytEtaVrrc

1. 安装 vscode、 blender

1
2
3
4
5
6
scoop install vscode
scoop install blender

# blender 和内置的 python 路径如下:
# blender path : C:\Users\xxxx\scoop\apps\blender\4.2.3\blender.exe
# blender build-in python path : C:\Users\shenb\scoop\apps\blender\4.2.3\4.2\python\bin\python.exe

在 vscode 中选择 python 解释器,注意选择 blender 内置的 python 路径。

2. 安装自动补全 fake-bpy-module

安装时注意要选用 blender 内置的 python -m pip 安装。

ref: https://github.com/nutti/fake-bpy-module

1
2
3
4
5
C:\Users\shenb\scoop\apps\blender\4.2.3\4.2\python\bin\python.exe -m pip install fake-bpy-module

# 安装常用的其他包:
# C:\Users\shenb\scoop\apps\blender\4.2.3\4.2\python\bin\python.exe -m pip install pandas
# C:\Users\shenb\scoop\apps\blender\4.2.3\4.2\python\bin\python.exe -m pip install matplotlib
阅读全文 »

视频内字幕提取

video-subtitles-ocr

视频字幕提取,基于 opencv 和 paddleocr

视频内字幕提取

这里是针对内封了硬字幕的视频,字幕已经成为了画面的一部分。

思路:简单用 opencv 提取视频内的所有帧,现在可以使用 paddleocr,更加方便一点对图片进行 ocr 识别。

0. 首先需要配置一下

0.1 安装 python 库

  • opencv-python
  • scikit-image
  • paddleocr

ref: https://paddlepaddle.github.io/PaddleOCR/latest/quick_start.html#1-paddlepaddle

阅读全文 »

word 不能直接导入 eps 格式的图片,所以先将 eps 图片转换成 png 格式。

这里使用 python 调用 PIL 读取 eps 图片,直接保存为 png 图片

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

# pip install pillow
# scoop install ghostscript

from PIL import Image

import os

for parent, dirnames, filenames in os.walk(os.getcwd()):
for filename in filenames:
ext = os.path.splitext(filename)[1]
if ext != '.eps':
continue

eps_image = Image.open(filename)
size = eps_image.size
print(filename, size)

eps_image.load(scale=10) # 分辨率增大到10倍
eps_image.save(filename+'.png', quality=100)
  • PIL 默认采用 Ghostscript 处理 eps 图片, 所以先确保安装了 Ghostscript。 scoop install ghostscript
  • eps 为矢量图,默认情况下其尺寸较小,导致保存成图片式分辨率较低,eps_image.load(scale=10) 将分辨率增大到10倍后保存。

下载 bili 视频

1
2
3
4
5
6
7
pip install you-get
# you-get https://www.bilibili.com/video/BV1234567890

pip install yt-dlp
# yt-dlp https://www.bilibili.com/video/BV1234567890

# yt-dlp "https://www.youtube.com/watch?v=GGGGGGGGGGGG" --proxy http://127.0.0.1:7890

视频转音频

1
2
3
4
5
6
scoop install ffmpeg
ffmpeg -i xxx.mp4
# checkout the audio video format
ffmpeg -i xxx.mp4 -acodec copy xxx.aac
ffmpeg -i xxx.mp4 -acodec copy xxx.mp3
ffmpeg -i xxx.mkv -acodec copy xxx.opus

音频转文字 📘

https://github.com/openai/whisper

  1. ** whisper **:
1
2
3
4
pip install -U openai-whisper

whisper audio.flac audio.mp3 audio.wav --model small --device cpu --language zh

  1. ** python **:
    使用 Python 运行 main.py 脚本。
1
2
3
4
5
6
import whisper

model = whisper.load_model("small", device="cpu")
result = model.transcribe(f"123.mp3")

print(result["text"]))

cat-catch 设置 N_m3u8DL-RE

ref https://github.com/nilaoda/N_m3u8DL-RE
ref https://github.com/xifangczy/cat-catch
ref https://github.com/corbamico/m3u8dl-invoke/

1.1 电脑安装 n-m3u8dl-re 软件

1
scoop install n-m3u8dl-re_x

1.2 Edge 浏览器安装 cat-catch 插件

设置 - N_m3u8DL-RE 的参数:

1
"${url}" --save-dir "%USERPROFILE%\Downloads\m3u8dl" --save-name "${title}_${now}" ${referer|exists:'-H "Referer:*"'} --del-after-done --no-log

1.3 添加 m3u8dl协议

  • 使用 https://github.com/xifangczy/URLProtocol 工具。
  • 下载URLProtocol和N_m3u8DL-RE 并放置在一起。
  • 打开URLProtocol工具,协议名填写 m3u8dl 点击选择目标程序按钮,选择N_m3u8DL-RE.exe 点击添加。

1.4 添加 m3u8dl协议(另一种方法)

阅读全文 »

matplotlib marker color 字符对照

ref: https://matplotlib.org/stable/api/colors_api.html
ref: https://matplotlib.org/stable/gallery/color/named_colors.html

1
2
3
4
5
6
7
8
9
10
11

import matplotlib.pyplot as plt
import matplotlib.colors as mcolors

for (k, v) in mcolors.BASE_COLORS.items():
v = "#" + "".join(format(round(val * 255), "02x") for val in v)
print(f'<font color="{v}"> {k:<10} ■ </font>')

for (k, v) in mcolors.TABLEAU_COLORS.items():
print(f'<font color="{v}"> {k:<10} ■ </font>')

mcolors.BASE_COLORS (8)

████ b
████ g
████ r
████ c
████ m
████ y
████ k
████ w

mcolors.TABLEAU_COLORS (10)

████ tab:blue
████ tab:orange
████ tab:green
████ tab:red
████ tab:purple
████ tab:brown
████ tab:pink
████ tab:gray
████ tab:olive
████ tab:cyan

阅读全文 »

文件夹禁用文件类型识别

文件夹启动时默认会识别该文件夹内的文件类型(比如图片、音乐、视频等媒体文件的信息),媒体文件过多时加载速度较慢。

可以禁用此功能。

1
2
3
4
5
6
# 管理员运行运行后重启:
reg add "HKCU\SOFTWARE\Classes\Local Settings\Software\Microsoft\Windows\Shell\Bags\AllFolders\Shell" /v "FolderType" /t REG_SZ /d "NotSpecified" /f

# 恢复默认:
# reg.exe delete "HKCU\SOFTWARE\Classes\Local Settings\Software\Microsoft\Windows\Shell\Bags\AllFolders\Shell" /f

Python f-string 备忘单

ref https://fstring.help/cheat/

ref https://cheatography.com/brianallan/cheat-sheets/python-f-strings-basics/
ref https://cheatography.com/brianallan/cheat-sheets/python-f-strings-number-formatting/

数字

num format
%d 整数
%e 科学计数
%f 浮点
% 百分数
%b 二进制
%o 八进制
%x 十六进制
%c Unicode

integer = 123
number_ = 9876.6789
percent = 0.98765

var num format f-string output
integer 123 d f’{integer:d}’ 123
integer 123 b f’{integer:b}’ 1111011
integer 123 8b f’{integer:8b}’ 1111011
integer 123 _b f’{integer:_b}’ 111_1011
integer 123 09_b f’{integer:09_b}’ 0111_1011
integer 123 o f’{integer:o}’ 173
integer 123 #o f’{integer:#o}’ 0o173
integer 123 x f’{integer:x}’ 7b
integer 123 #x f’{integer:#x}’ 0x7b
integer 123 08x f’{integer:08x}’ 0000007b
integer 123 c f’{integer:c}’ {
number_ 9876.6789 f f’{number_:f}’ 9876.678900
number_ 9876.6789 .2f f’{number_:.2f}’ 9876.68
number_ 9876.6789 09.2f f’{number_:09.2f}’ 009876.68
number_ 9876.6789 09.5f f’{number_:09.5f}’ 9876.67890
number_ 9876.6789 .2f f’{number_:.2f}’ 9876.68
percent 0.98765 % f’{percent:%}’ 98.765000%
percent 0.98765 9.5% f’{percent:9.5%}’ 98.76500%
percent 0.98765 09.4% f’{percent:09.4%}’ 098.7650%
percent 0.98765 09.5% f’{percent:09.5%}’ 98.76500%
number_ 9876.6789 .2e f’{number_:.2e}’ 9.88e+03
number_ 9876.6789 09.2e f’{number_:09.2e}’ 09.88e+03

string = “Python”

var num format f-string output
string Python 20 f’{string:20}’ Python
string Python >20 f’{string:>20}’ Python
string Python <20 f’{string:<20}’ Python
string Python ^20 f’{string:^20}’ Python
string Python >>20 f’{string:>>20}’ >>>>>>>>>>>>>>Python
string Python <<20 f’{string:<<20}’ Python<<<<<<<<<<<<<<
string Python ^^20 f’{string:^^20}’ ^^^^^^^Python^^^^^^^
string Python =^20 f’{string:=^20}’ =======Python=======
阅读全文 »

radioactivedecay 用于放射性核素衰变的简单分析计算的开源包,支持放射性核素、亚稳态和分支衰变的衰变链。

https://github.com/radioactivedecay/radioactivedecay

安装:pip install radioactivedecay

1. 绘制衰变链

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#%%
import radioactivedecay as rd
import matplotlib.pyplot as plt

# 创建一个放射性核素: Nuclide
ncld = rd.Nuclide('U-235')
half = ncld.half_life('readable') # 半衰期
prog = ncld.progeny() # 衰变产物
frac = ncld.branching_fractions() # 占比
mode = ncld.decay_modes() # 衰变射线类型

print(ncld, mode, prog, frac, half, sep='\n')

# 绘制衰变链
ncld.plot()

#%%
# 列出多个核算衰变类型
NUCs = ['U-235',
'Pu-239']

for name in NUCs:
ncld = rd.Nuclide(name)
half = ncld.half_life('readable')
prog = ncld.progeny()
frac = ncld.branching_fractions()
mode = ncld.decay_modes()
print(ncld, mode, prog, frac, half, sep='\n')

fig, ax = ncld.plot()
fig.savefig(f'decay_chains_{name}.png', dpi=300)

阅读全文 »