upload
This commit is contained in:
Binary file not shown.
@@ -0,0 +1,256 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import annotations
|
||||
|
||||
"""按 workid 列出 categorylist2 一级分类,勾选要剔除的 tag1_name,写入 poi_category_filter 黑名单。
|
||||
|
||||
说明:poi_category_filter 为黑名单表,表里的分类会在 run_pro2 / 数据迁移 中被剔除。
|
||||
|
||||
用法:python exclude_tag1_filter.py
|
||||
也可改顶部 WORKID / USE_BATCH_FIELD 后直接运行。
|
||||
"""
|
||||
|
||||
import datetime
|
||||
import io
|
||||
import sys
|
||||
from contextlib import redirect_stdout
|
||||
|
||||
import newsetting as ten
|
||||
|
||||
# ==================== 运行参数(改这里) ====================
|
||||
WORKID = 'upc_all_20260804' # 留空则运行时输入,例: 20260709
|
||||
USE_BATCH_FIELD = True # True 时用 batch LIKE '%workid%' 过滤
|
||||
# ============================================================
|
||||
|
||||
tent = ten.All_Setting(host='192.168.5.2', port=3307, db='pyui_all_market')
|
||||
|
||||
INSERT_SQL = '''
|
||||
INSERT IGNORE INTO poi_category_filter
|
||||
(workid, poi_id_str, shop_name, tag1, tag1_name, tag2, tag2_name)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s)
|
||||
'''
|
||||
|
||||
|
||||
def _db_query(sql: str):
|
||||
with redirect_stdout(io.StringIO()):
|
||||
return tent.get_shoppingmalls(sql)
|
||||
|
||||
|
||||
def _db_write_batch(sql: str, data: list[tuple]):
|
||||
with redirect_stdout(io.StringIO()):
|
||||
tent.write_data(sql, data)
|
||||
|
||||
|
||||
def _sql_str(value) -> str:
|
||||
return "'" + str(value).replace("'", "''") + "'"
|
||||
|
||||
|
||||
def _workid_clause(workid: str) -> str:
|
||||
if USE_BATCH_FIELD:
|
||||
return f"batch LIKE '%{workid.replace(chr(39), chr(39)+chr(39))}%'"
|
||||
return f"workid = {_sql_str(workid)}"
|
||||
|
||||
|
||||
def fetch_tag1_names(workid: str) -> list[tuple[str, int]]:
|
||||
"""返回 [(tag1_name, 行数), ...] 按名称排序。"""
|
||||
clause = _workid_clause(workid)
|
||||
sql = f'''
|
||||
SELECT tag1_name, COUNT(*) AS cnt
|
||||
FROM categorylist2
|
||||
WHERE {clause}
|
||||
AND tag1_name IS NOT NULL
|
||||
AND TRIM(tag1_name) != ''
|
||||
GROUP BY tag1_name
|
||||
ORDER BY tag1_name
|
||||
'''
|
||||
rows = _db_query(sql)
|
||||
return [(str(r[0]).strip(), int(r[1])) for r in rows]
|
||||
|
||||
|
||||
def fetch_excluded_rows(workid: str, excluded: set[str]) -> list[tuple]:
|
||||
"""把勾选的一级分类对应行写入黑名单。"""
|
||||
clause = _workid_clause(workid)
|
||||
sql = f'''
|
||||
SELECT poi_id_str, shop_name, tag1, tag1_name, tag2, tag2_name
|
||||
FROM categorylist2
|
||||
WHERE {clause}
|
||||
AND tag1_name IS NOT NULL
|
||||
AND TRIM(tag1_name) != ''
|
||||
'''
|
||||
rows = _db_query(sql)
|
||||
seen: set[tuple] = set()
|
||||
result: list[tuple] = []
|
||||
for poi_id_str, shop_name, tag1, tag1_name, tag2, tag2_name in rows:
|
||||
poi = str(poi_id_str or '').strip()
|
||||
shop = str(shop_name or '').strip()
|
||||
t1n = str(tag1_name or '').strip()
|
||||
if not poi or not t1n or t1n not in excluded:
|
||||
continue
|
||||
key = (poi, shop, str(tag1 or ''), t1n, str(tag2 or ''), str(tag2_name or ''))
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
result.append(key)
|
||||
return result
|
||||
|
||||
|
||||
def _parse_selection(text: str, max_no: int) -> set[int]:
|
||||
"""解析 1,3,5-8 这类输入,返回 1-based 序号集合。"""
|
||||
text = text.replace(',', ',').replace(' ', '')
|
||||
if not text:
|
||||
return set()
|
||||
|
||||
chosen: set[int] = set()
|
||||
for part in text.split(','):
|
||||
if not part:
|
||||
continue
|
||||
if '-' in part:
|
||||
a, b = part.split('-', 1)
|
||||
if not a.isdigit() or not b.isdigit():
|
||||
raise ValueError(f'无效范围: {part}')
|
||||
start, end = int(a), int(b)
|
||||
if start > end:
|
||||
start, end = end, start
|
||||
for i in range(start, end + 1):
|
||||
if 1 <= i <= max_no:
|
||||
chosen.add(i)
|
||||
continue
|
||||
if not part.isdigit():
|
||||
raise ValueError(f'无效序号: {part}')
|
||||
n = int(part)
|
||||
if 1 <= n <= max_no:
|
||||
chosen.add(n)
|
||||
return chosen
|
||||
|
||||
|
||||
def _parse_keywords(text: str) -> list[str]:
|
||||
"""支持: kw:组合,优惠 或 关键词:组合,优惠 或 纯中文逗号列表(不含纯数字)。"""
|
||||
raw = text.strip()
|
||||
lower = raw.lower()
|
||||
for prefix in ('kw:', 'keyword:', 'keywords:', '关键词:', '关键词:'):
|
||||
if lower.startswith(prefix) or raw.startswith(prefix):
|
||||
raw = raw[len(prefix):]
|
||||
break
|
||||
raw = raw.replace(',', ',').replace(' ', '')
|
||||
keys = [k for k in raw.split(',') if k]
|
||||
if not keys:
|
||||
raise ValueError('未解析到关键词')
|
||||
# 若全是数字/范围,当作序号而非关键词
|
||||
if all(p.replace('-', '').isdigit() for p in keys):
|
||||
raise ValueError('看起来是序号输入,请走序号解析')
|
||||
return keys
|
||||
|
||||
|
||||
def _match_by_keywords(items: list[tuple[str, int]], keywords: list[str]) -> set[int]:
|
||||
"""分类名包含任一关键词则选中(1-based 序号)。"""
|
||||
chosen: set[int] = set()
|
||||
for idx, (name, _) in enumerate(items, 1):
|
||||
if any(kw in name for kw in keywords):
|
||||
chosen.add(idx)
|
||||
return chosen
|
||||
|
||||
|
||||
def _print_tag_list(items: list[tuple[str, int]]):
|
||||
total_rows = sum(c for _, c in items)
|
||||
print(f'\n共 {len(items)} 个一级分类,合计 {total_rows} 行\n')
|
||||
print(f'{"序号":>4} {"行数":>6} 分类名')
|
||||
print('-' * 50)
|
||||
for idx, (name, cnt) in enumerate(items, 1):
|
||||
print(f'{idx:>4} {cnt:>6} {name}')
|
||||
print('-' * 50)
|
||||
|
||||
|
||||
def _ask_workid() -> str:
|
||||
default = WORKID or datetime.date.today().strftime('%Y%m%d')
|
||||
raw = input(f'workid [{default}]: ').strip()
|
||||
return raw or default
|
||||
|
||||
|
||||
def _ask_excluded(items: list[tuple[str, int]]) -> set[str]:
|
||||
_print_tag_list(items)
|
||||
print('\n请输入要【剔除】的分类序号(多选用逗号,范围用 1-5,回车=不剔除)')
|
||||
print('例: 3,7,12-15')
|
||||
print('也可用关键词: kw:组合,优惠 或直接输入 组合,优惠')
|
||||
print('输入 q 退出')
|
||||
while True:
|
||||
line = input('>>> ').strip()
|
||||
if line.lower() in ('q', 'quit', 'exit'):
|
||||
raise SystemExit(0)
|
||||
if not line:
|
||||
return set()
|
||||
try:
|
||||
# 优先尝试关键词(含中文 / kw: 前缀)
|
||||
use_kw = False
|
||||
lower = line.lower()
|
||||
if any(lower.startswith(p) or line.startswith(p) for p in (
|
||||
'kw:', 'keyword:', 'keywords:', '关键词:', '关键词:',
|
||||
)):
|
||||
use_kw = True
|
||||
elif any('\u4e00' <= ch <= '\u9fff' for ch in line):
|
||||
use_kw = True
|
||||
|
||||
if use_kw:
|
||||
keywords = _parse_keywords(line)
|
||||
picked = _match_by_keywords(items, keywords)
|
||||
print(f'[关键词] {keywords} → 命中 {len(picked)} 个分类')
|
||||
else:
|
||||
picked = _parse_selection(line, len(items))
|
||||
except ValueError as e:
|
||||
print(f'[错误] {e}')
|
||||
continue
|
||||
if not picked:
|
||||
print('[提示] 未选中任何序号,请重试')
|
||||
continue
|
||||
excluded = {items[i - 1][0] for i in sorted(picked)}
|
||||
print('\n将剔除以下一级分类:')
|
||||
for i in sorted(picked):
|
||||
name, cnt = items[i - 1]
|
||||
print(f' {i:>4} ({cnt}行) {name}')
|
||||
confirm = input('确认? [y/N]: ').strip().lower()
|
||||
if confirm in ('y', 'yes'):
|
||||
return excluded
|
||||
print('已取消,请重新选择')
|
||||
|
||||
|
||||
def insert_rows(workid: str, rows: list[tuple]) -> int:
|
||||
if not rows:
|
||||
print('[提示] 没有需要写入的分类行')
|
||||
return 0
|
||||
|
||||
payload = [
|
||||
(workid, poi, shop, tag1, tag1_name, tag2, tag2_name)
|
||||
for poi, shop, tag1, tag1_name, tag2, tag2_name in rows
|
||||
]
|
||||
_db_write_batch(INSERT_SQL, payload)
|
||||
return len(payload)
|
||||
|
||||
|
||||
def main():
|
||||
workid = WORKID.strip() or _ask_workid()
|
||||
field = 'batch' if USE_BATCH_FIELD else 'workid'
|
||||
print(f'[参数] workid={workid} | 过滤字段={field} | 库=pyui_all_market | 模式=黑名单')
|
||||
|
||||
items = fetch_tag1_names(workid)
|
||||
if not items:
|
||||
print(f'[无数据] categorylist2 中未找到 {field}={workid} 的分类')
|
||||
return
|
||||
|
||||
excluded = _ask_excluded(items)
|
||||
if not excluded:
|
||||
print('[结束] 未选择剔除项,未写入数据库')
|
||||
return
|
||||
|
||||
rows = fetch_excluded_rows(workid, excluded)
|
||||
print(f'\n[预览] 将写入 poi_category_filter 黑名单 {len(rows)} 条')
|
||||
print(f' 剔除一级分类 {len(excluded)} 个')
|
||||
|
||||
go = input('写入数据库? [y/N]: ').strip().lower()
|
||||
if go not in ('y', 'yes'):
|
||||
print('[取消] 未写入')
|
||||
return
|
||||
|
||||
n = insert_rows(workid, rows)
|
||||
print(f'[完成] 已提交 {n} 条 (INSERT IGNORE,重复自动跳过)')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,82 @@
|
||||
import re
|
||||
import pymysql
|
||||
|
||||
class All_Setting():
|
||||
def __init__(self,host,port,db):
|
||||
self.host = host
|
||||
self.port = port
|
||||
self.db = db
|
||||
|
||||
def remove_symbols(self,text):
|
||||
pattern = re.compile(r'[^\w\s]')
|
||||
return pattern.sub('', text)
|
||||
|
||||
def get_chinese(self,text,printTxt=False):
|
||||
pattern = r'[^\w\s]'
|
||||
result = re.sub(pattern, '', text)
|
||||
if printTxt:
|
||||
print(result)
|
||||
return result
|
||||
|
||||
def get_shoppingmalls(self,sql):
|
||||
conn = pymysql.connect(
|
||||
host= self.host,
|
||||
port=self.port,
|
||||
user='root',
|
||||
password='Aliyun@7646!',
|
||||
db=self.db,
|
||||
charset='utf8mb4'
|
||||
)
|
||||
if conn:
|
||||
print('ok')
|
||||
cursor = conn.cursor()
|
||||
cursor.execute(sql)
|
||||
return cursor.fetchall()
|
||||
|
||||
def write_data(self,sql,data):
|
||||
conn = pymysql.connect(
|
||||
host= self.host,
|
||||
port=self.port,
|
||||
user='root',
|
||||
password='Aliyun@7646!',
|
||||
db=self.db,
|
||||
charset='utf8mb4'
|
||||
)
|
||||
if conn:
|
||||
print("连接成功!")
|
||||
cursor = conn.cursor()
|
||||
cursor.executemany(sql,data)
|
||||
conn.commit()
|
||||
cursor.close()
|
||||
|
||||
def update_data(self,sql):
|
||||
conn = pymysql.connect(
|
||||
host= self.host,
|
||||
port=self.port,
|
||||
user='root',
|
||||
password='Aliyun@7646!',
|
||||
db=self.db,
|
||||
charset='utf8mb4'
|
||||
)
|
||||
if conn:
|
||||
print("连接成功!")
|
||||
cursor = conn.cursor()
|
||||
cursor.execute(sql)
|
||||
conn.commit()
|
||||
cursor.close()
|
||||
|
||||
def write_data_one(self,sql,data):
|
||||
conn = pymysql.connect(
|
||||
host= self.host,
|
||||
port=self.port,
|
||||
user='root',
|
||||
password='Aliyun@7646!',
|
||||
db=self.db,
|
||||
charset='utf8mb4'
|
||||
)
|
||||
if conn:
|
||||
print("连接成功!")
|
||||
cursor = conn.cursor()
|
||||
cursor.execute(sql,data)
|
||||
conn.commit()
|
||||
cursor.close()
|
||||
Reference in New Issue
Block a user