我正在嘗試通過對其應用 REGEXP 模式來操作字串列。
所有值實際上都是浮點數,但轉換為字串。要點是從數字中洗掉任何尾隨零,如下所示。
input -> output
1.000 -> 1
1.100 -> 1.1
1.001 -> 1.001
0.001 -> 0.001
0.010 -> 0.01
我可以使用 REGEXP^(\d (?:\.\d*?[1-9](?=0|\b))?)\.?0*$來實作上面所示的here。
問題:如何使用 SQLalchemy 將上述 REGEXP 應用于字串列的所有行?操作必須在資料庫端完成,由于資料的大小,不能將資料移出資料庫。
Postgres 等價物是:
select TRIM(trailing '00' FROM CAST(numeric_col::decimal(32, 8) as text))
from my_table;
任何幫助表示贊賞。
uj5u.com熱心網友回復:
給定這樣的表:
test# table t71689267;
id │ col
════╪═══════
1 │ 1.000
2 │ 1.100
3 │ 1.001
4 │ 0.001
5 │ 0.010
你可以在 Postgresql 中這樣做*(注意regexp_match回傳一個陣列):
test# select col, regexp_match(col, '^(\d (?:\.\d*?[^0])?)\.?0*$') from t71689267;
col │ regexp_match
═══════╪══════════════
1.000 │ {1}
1.100 │ {1.1}
1.001 │ {1.001}
0.001 │ {0.001}
0.010 │ {0.01}
SQLAlchemy 中的等價物是
import sqlalchemy as sa
...
with engine.connect() as conn:
# tbl is a SQLAlchemy Table instance corresponding to the table in the database
q = sa.select(sa.func.regexp_match(tbl.c.col, r'^(\d (?:\.\d*?[^0])?)\.?0*$'))
rows = conn.execute(q)
for row in rows.scalars():
print(row)
print()
給予
['1']
['1.1']
['1.001']
['0.001']
['0.01']
* 問題中的模式似乎不適用于所有情況;我使用的那個適用于問題中的所有字串。您當然可以替換您想要使用的任何模式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/453905.html
標籤:Python 正则表达式 PostgreSQL sqlalchemy
