如何用Python或PL/SQL将非JSON类字典文本解析为表格?
解析带u前缀的类字典字符串为表格
Python 实现方法
这种带u'前缀的字符串是Python 2里的Unicode字典表示,用ast.literal_eval就能安全解析,比直接用eval更稳妥。
具体步骤和代码:
import ast import pandas as pd # 读取目标文本文件 with open('products.txt', 'r', encoding='utf-8') as f: lines = [line.strip() for line in f if line.strip()] # 逐行解析并整理数据 product_list = [] for line in lines: # 把字符串转成Python字典 product_dict = ast.literal_eval(line) product_list.append({ 'Product_id': product_dict['Product_id'], 'Product_name': product_dict['Product_name'], 'Product_code': product_dict['Product_code'] }) # 生成规整表格并打印 df = pd.DataFrame(product_list) print(df.to_string(index=False))
运行后输出结果:
Product_id Product_name Product_code 1234567 Apple 2.4.14 1234123 Orange 2.4.20
PL/SQL 实现方法
Oracle PL/SQL里只能靠字符串处理函数提取字段,这里用REGEXP_SUBSTR正则匹配来提取每个键对应的值。
场景1:数据已存入表中
假设原始字符串存在product_raw表的raw_data字段,每行一条记录,执行以下SQL即可提取:
SELECT REGEXP_SUBSTR(raw_data, "'Product_id': u'([^']+)'", 1, 1, 'i', 1) AS Product_id, REGEXP_SUBSTR(raw_data, "'Product_name': u'([^']+)'", 1, 1, 'i', 1) AS Product_name, REGEXP_SUBSTR(raw_data, "'Product_code': u'([^']+)'", 1, 1, 'i', 1) AS Product_code FROM product_raw;
场景2:直接处理单行字符串
写PL/SQL块解析单个字符串:
DECLARE v_raw_str VARCHAR2(1000) := '{u''Product_id'': u''1234567'', u''Product_name'': u''Apple'', u''Product_code'': u''2.4.14''}'; v_product_id VARCHAR2(20); v_product_name VARCHAR2(50); v_product_code VARCHAR2(20); BEGIN v_product_id := REGEXP_SUBSTR(v_raw_str, '''Product_id'': u''([^'']+)''', 1, 1, 'i', 1); v_product_name := REGEXP_SUBSTR(v_raw_str, '''Product_name'': u''([^'']+)''', 1, 1, 'i', 1); v_product_code := REGEXP_SUBSTR(v_raw_str, '''Product_code'': u''([^'']+)''', 1, 1, 'i', 1); DBMS_OUTPUT.PUT_LINE('Product_id: ' || v_product_id); DBMS_OUTPUT.PUT_LINE('Product_name: ' || v_product_name); DBMS_OUTPUT.PUT_LINE('Product_code: ' || v_product_code); END; /
内容的提问来源于stack exchange,提问作者Tom Tom
相关产品推荐
相关产品推荐

