Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

update #117

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,6 @@ MANIFEST
.mr.developer.cfg
.project
.pydevproject
*.txt
*.csv
.idea
3 changes: 3 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"python.analysis.autoImportCompletions": true
}
15 changes: 15 additions & 0 deletions samples/commonlib/use_datetime.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,18 @@
utc8_dt = utc_dt.astimezone(timezone(timedelta(hours=8)))
print('UTC+0:00 now =', utc_dt)
print('UTC+8:00 now =', utc8_dt)

import datetime

target_date = datetime.datetime(2024, 2, 2, 18, 0, 0) # 目标日期和时间
current_datetime = datetime.datetime.now() # 当前日期和时间

time_left = target_date - current_datetime # 计算剩余时间
time_left = max(time_left, datetime.timedelta(0)) # 确保剩余时间不为负值

# 提取剩余时间的小时、分钟和秒
hours, remainder = divmod(time_left.total_seconds(), 3600)
minutes, seconds = divmod(remainder, 60)

# 输出倒计时信息
print(f"当前时间与2024-02-02 18:00:00之间相隔 {int(hours)} 小时 {int(minutes)} 分钟 {int(seconds)} 秒")
15 changes: 15 additions & 0 deletions samples/commonlib/use_datetime_copy.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@

import datetime

target_date = datetime.datetime(2024, 2, 2, 18, 0, 0) # 目标日期和时间
current_datetime = datetime.datetime.now() # 当前日期和时间

time_left = target_date - current_datetime # 计算剩余时间
time_left = max(time_left, datetime.timedelta(0)) # 确保剩余时间不为负值

# 提取剩余时间的小时、分钟和秒
hours, remainder = divmod(time_left.total_seconds(), 3600)
minutes, seconds = divmod(remainder, 60)

# 输出倒计时信息
print(f"当前时间与2024-02-02 18:00:00之间相隔 {int(hours)} 小时 {int(minutes)} 分钟 {int(seconds)} 秒")
62 changes: 48 additions & 14 deletions samples/db/do_mysql.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,25 +7,59 @@
# pip3 install mysql-connector-python --allow-external mysql-connector-python

import mysql.connector
import pandas as pd
import numpy as np
import re

# change root password to yours:
conn = mysql.connector.connect(user='root', password='password', database='test')

cursor = conn.cursor()
# 创建user表:
cursor.execute('create table user (id varchar(20) primary key, name varchar(20))')
# 插入一行记录,注意MySQL的占位符是%s:
cursor.execute('insert into user (id, name) values (%s, %s)', ('1', 'Michael'))
print('rowcount =', cursor.rowcount)
# 提交事务:
conn.commit()
cursor.close()
conn = mysql.connector.connect(user='root', password='root', database='sys')

# 运行查询:
cursor = conn.cursor()
cursor.execute('select * from user where id = %s', ('1',))
cursor.execute('select 患者编号,中药组成 from Sheet4 ')
values = cursor.fetchall()
print(values)
# 关闭Cursor和Connection:

# 获取查询结果的字段名
columns = [i[0] for i in cursor.description]

# 关闭 Cursor 和 Connection
cursor.close()
conn.close()

# 创建 DataFrame,并指定列名
df = pd.DataFrame(values, columns=columns)

# 提取中文和数字字母的正则表达式
pattern = re.compile(r'([\u4e00-\u9fa5]+)(\d+\w+)')
result = df['中药组成'].str.extractall(pattern)


# 保存原始的患者编号列
patient_ids = df['患者编号'].iloc[result.index.get_level_values(0)].reset_index(drop=True)

# 重置索引
result.reset_index(drop=True, inplace=True)


# 将患者编号加回结果中
result['患者编号'] = patient_ids

# 重新排列列的顺序
result = result[['患者编号', 0, 1]]
# 重命名列名
result.columns = ['患者编号', '草药', '克数']
# 打印 result 的所有内容
print(result)

# 将数据插入新表
connInsert = mysql.connector.connect(user='root', password='root', database='sys')
cursorInsert = connInsert.cursor()

# 使用 iterrows() 迭代 DataFrame 中的行
for _, row in result.iterrows():
cursorInsert.execute('INSERT INTO Sheet4_detail (患者编号, 中药, 克数) VALUES (%s, %s, %s)', (row['患者编号'], row['草药'], row['克数']))

# 提交更改并关闭连接
connInsert.commit()
cursorInsert.close()
connInsert.close()
49 changes: 49 additions & 0 deletions samples/matplotlib/matplotlibPd copy 2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator

# 读取CSV文件数据
df = pd.read_csv(r'D:\pyspace\learn-python3\samples\matplotlib\含远至功效.csv')

# 设置中文显示的字体
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

# 若百分比数据为字符串形式,需要将其转换为数值形式
# 此行代码假设百分比列的值包含%符号,如'22.42%'
df['百分比'] = df['百分比'].str.rstrip('%').astype('float')

# 绘制图表
fig, ax = plt.subplots(figsize=(12, 6))

# 以天蓝色作为颜色绘制频次柱状图
ax.bar(df['功效统计分析'], df['频次'], color='skyblue')

# 设置坐标轴标签
# ax.set_xlabel('功效统计分析')
ax.set_ylabel('频次')

# 以红色圆圈绘制百分比折线图
ax2 = ax.twinx()
ax2.plot(df['功效统计分析'], df['百分比'], 'ro-')
ax2.set_ylabel('百分比 (%)')

# Set Y axis major ticks to a multiple of 1
ax2.yaxis.set_major_locator(MultipleLocator(1))

# 去掉网格线
ax.grid(False)

# 在每个柱子上方标识频次数量值
for bar in ax.patches:
ax.text(bar.get_x() + bar.get_width()/2,
bar.get_height(),
'{:.0f}'.format(bar.get_height()),
ha='center',
va='bottom')

# 调整整体空白,防止标签重叠
fig.tight_layout()

# 显示图表
plt.show()
45 changes: 45 additions & 0 deletions samples/matplotlib/matplotlibPd copy.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import pandas as pd
import matplotlib.pyplot as plt

# 读取CSV文件数据
df = pd.read_csv(r'D:\pyspace\learn-python3\samples\matplotlib\去远至功效.csv')

# 设置中文显示的字体
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

# 若百分比数据为字符串形式,需要将其转换为数值形式
# 此行代码假设百分比列的值包含%符号,如'22.42%'
df['百分比'] = df['百分比'].str.rstrip('%').astype('float')

# 绘制图表
fig, ax = plt.subplots(figsize=(12, 6))

# 以天蓝色作为颜色绘制频次柱状图
ax.bar(df['去远至功效'], df['频次'], color='skyblue')

# 设置坐标轴标签
# ax.set_xlabel('去远至功效')
ax.set_ylabel('频次')

# 以红色圆圈绘制百分比折线图
ax2 = ax.twinx()
ax2.plot(df['去远至功效'], df['百分比'], 'ro-')
ax2.set_ylabel('百分比 (%)')

# 去掉网格线
ax.grid(False)

# 在每个柱子上方标识频次数量值
for bar in ax.patches:
ax.text(bar.get_x() + bar.get_width()/2,
bar.get_height(),
'{:.0f}'.format(bar.get_height()),
ha='center',
va='bottom')

# 调整整体空白,防止标签重叠
fig.tight_layout()

# 显示图表
plt.show()
45 changes: 45 additions & 0 deletions samples/matplotlib/matplotlibPd.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import pandas as pd
import matplotlib.pyplot as plt

# 读取CSV文件数据
df = pd.read_csv(r'D:\pyspace\learn-python3\samples\matplotlib\中医症候.csv')

# 设置中文显示的字体
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

# 若百分比数据为字符串形式,需要将其转换为数值形式
# 此行代码假设百分比列的值包含%符号,如'22.42%'
df['百分比'] = df['百分比'].str.rstrip('%').astype('float')

# 绘制图表
fig, ax = plt.subplots(figsize=(12, 6))

# 以天蓝色作为颜色绘制频次柱状图
ax.bar(df['中医证候'], df['频次'], color='skyblue')

# 设置坐标轴标签
# ax.set_xlabel('中医证候')
ax.set_ylabel('频次')

# 以红色圆圈绘制百分比折线图
ax2 = ax.twinx()
ax2.plot(df['中医证候'], df['百分比'], 'ro-')
ax2.set_ylabel('百分比 (%)')

# 去掉网格线
ax.grid(False)

# 在每个柱子上方标识频次数量值
for bar in ax.patches:
ax.text(bar.get_x() + bar.get_width()/2,
bar.get_height(),
'{:.0f}'.format(bar.get_height()),
ha='center',
va='bottom')

# 调整整体空白,防止标签重叠
fig.tight_layout()

# 显示图表
plt.show()
Binary file added samples/matplotlib/output.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading