functions.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import re, ast, requests
  2. import math, json
  3. def save_dict_to_json(dictionary, filename):
  4. with open(filename, 'w', encoding='utf-8') as file:
  5. json.dump(dictionary, file, ensure_ascii=False, indent=4)
  6. def load_dict_from_json(filename):
  7. with open(filename, 'r', encoding='utf-8') as file:
  8. return json.load(file)
  9. def split_dataframe_to_dict(df, chunk_size=100):
  10. # 计算需要切割的份数
  11. num_chunks = math.ceil(len(df) / chunk_size)
  12. # 用于存储结果的字典
  13. result_dict = {}
  14. for i in range(num_chunks):
  15. # 切割 DataFrame
  16. start = i * chunk_size
  17. end = min((i + 1) * chunk_size, len(df))
  18. chunk = df.iloc[start:end]
  19. # 将切割后的 DataFrame 转换为字典并存储
  20. result_dict[f'chunk_{i+1}'] = chunk.to_dict(orient='records')
  21. return result_dict
  22. def extract_list_from_string(input_string):
  23. # 使用正则表达式查找列表部分
  24. list_pattern = r'\[.*?\]'
  25. match = re.search(list_pattern, input_string, re.DOTALL)
  26. if match:
  27. list_string = match.group()
  28. try:
  29. # 使用 ast.literal_eval 安全地解析字符串
  30. result = ast.literal_eval(list_string)
  31. # 检查结果是否为列表
  32. if isinstance(result, list):
  33. return result
  34. else:
  35. print("解析结果不是列表")
  36. return None
  37. except Exception as e:
  38. print(f"解析错误: {e}")
  39. return None
  40. else:
  41. print("未找到列表结构")
  42. return None
  43. def post_openai(messages):
  44. Baseurl = "https://fast.bemore.lol"
  45. Skey = "sk-dxl4rt2wWswbdrCr1c7b8500B68c43F5B6175b90F7D672C4"
  46. payload = json.dumps({
  47. "model": "gpt-4",
  48. "messages": messages
  49. })
  50. url = Baseurl + "/v1/chat/completions"
  51. headers = {
  52. 'Accept': 'application/json',
  53. 'Authorization': f'Bearer {Skey}',
  54. 'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
  55. 'Content-Type': 'application/json'
  56. }
  57. response = requests.request("POST", url, headers=headers, data=payload)
  58. # 解析 JSON 数据为 Python 字典
  59. print(response)
  60. data = response.json()
  61. # 获取 content 字段的值
  62. content = data['choices'][0]['message']['content']
  63. return content