postgresql2csv.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. # DEPRECATED(Phase1): 本文件中的 PostgreSQL 硬编码连接(host=192.168.*,
  2. # password=postgres 等)将在后续 training/ Phase 迁移到 BiddingKG.dl.infra.db。
  3. # 迁移完成前可临时使用:from BiddingKG.dl.infra.db import get_connection;
  4. # conn = get_connection("<dbname>")
  5. # 详见 ARCHITECTURE.md 第 11 章 Phase 1 与 REFACTOR_LOG.md。
  6. import os
  7. import sys
  8. import time
  9. import pandas as pd
  10. import numpy as np
  11. import psycopg2
  12. sys.path.append(os.path.abspath("../../.."))
  13. from BiddingKG.dl.table_head.predict import predict
  14. def eval_text_list(table_text):
  15. if table_text[0] == '"':
  16. table_text = eval(table_text)
  17. else:
  18. table_text = table_text
  19. table_text = table_text.replace('\\', '/')
  20. table_text = eval(table_text)
  21. return table_text
  22. def read_postgresql(txt_name, start_id, _time):
  23. conn = psycopg2.connect(database="table_head_label", user="postgres",
  24. password="postgres", host="192.168.2.103", port="5432")
  25. row_list = []
  26. if txt_name == "":
  27. sql = """
  28. select * from "label_table_head_info"
  29. where status = 1 and update_time >= '2022-01-17';
  30. """
  31. df = pd.read_sql(sql=sql, con=conn)
  32. for index, row in df.iterrows():
  33. row_list.append([x for x in row])
  34. else:
  35. with open('check_user_result/' + txt_name, "r") as f:
  36. id_list = f.readlines()
  37. for _id in id_list:
  38. _id = _id[:-1]
  39. sql = 'select * from label_table_head_info where id =' + _id
  40. df = pd.read_sql(sql=sql, con=conn)
  41. # df = df[0]
  42. for index, row in df.iterrows():
  43. row_list.append([x for x in row])
  44. cnt = 0
  45. new_list = []
  46. for line in row_list:
  47. try:
  48. table_text = eval_text_list(line[2])
  49. except:
  50. print("无法识别")
  51. continue
  52. if cnt % 1000 == 0:
  53. print("Loop", cnt)
  54. line[0] = start_id + cnt
  55. cnt += 1
  56. line[6] = 'test'
  57. line[9] = 1
  58. if time == '':
  59. line[7] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
  60. else:
  61. line[7] = _time
  62. # 模型识别table_head
  63. label_list = predict(table_text)
  64. line[3] = str(label_list)
  65. new_list.append(line)
  66. df = pd.DataFrame(new_list)
  67. new_csv_path = "data_new.csv"
  68. df.to_csv(new_csv_path, index=False)
  69. conn.close()
  70. return new_csv_path
  71. if __name__ == '__main__':
  72. new_csv_path = read_postgresql('test11_error.txt', 206863, '2021-12-31 00:00:00')
  73. # new_csv_path = read_postgresql('test20_right.txt', 203995, '')
  74. # df = pd.read_csv('data_new.csv')
  75. # print(df.iloc[:, 4])