我正在使用 Python 和 SQL Alchemy 來自動化一些產品分類。本質上,我希望將任何帶有專案的 csv 作為行并將其格式化為 SQL 查詢的 case 陳述句的搜索字串。
我想在 python 中撰寫一個函式,該函式將測量行(或串列)的長度并在每個單詞之間插入文本并輸出一個字串,該字串將輸入 SQL 以查找這些單詞。隨附的螢屏截圖是我在 excel 中的操作方式。我敢肯定,對于具有一些串聯技能的人來說,這相當簡單。
腳本輸出示例
uj5u.com熱心網友回復:
在我看來,您可以從第一列中獲取值并將其拆分為串列以獲得所需的結果。
例如:
inputs = [
"Bootcut Yoga Pants",
"Go-Go Boots",
"Flower Print Mini Skirts",
]
for input in inputs:
# Split the item in to a list of individual words
items = input.split()
# Turn the list of words in to a list of query clauses
query_items = [f"item_name ilike '%{item}%'" for item in items]
# Turn that in to a string, with the word "and" between each item
query_line = " and ".join(query_items)
# Construct the final query
print(f"when {query_line} then '{input}'")
結果是:
when item_name ilike '%Bootcut%' and item_name ilike '%Yoga%' and item_name ilike '%Pants%' then 'Bootcut Yoga Pants'
when item_name ilike '%Go-Go%' and item_name ilike '%Boots%' then 'Go-Go Boots'
when item_name ilike '%Flower%' and item_name ilike '%Print%' and item_name ilike '%Mini%' and item_name ilike '%Skirts%' then 'Flower Print Mini Skirts'
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/435657.html
標籤:Python 功能 sqlalchemy 字符串连接
下一篇:如何為多載函式宣告模板引數
