process_trigger.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import pandas as pd
  2. import orjson
  3. import os
  4. def process_trigger_results(json_data):
  5. """
  6. Process the trigger results from the JSON data and write to Excel.
  7. Args:
  8. json_data (str): JSON string containing the trigger results
  9. """
  10. try:
  11. # Parse the JSON data
  12. data = orjson.loads(json_data)
  13. # Extract the output array from the data
  14. if isinstance(data, dict) and 'data' in data:
  15. output_data = orjson.loads(data['data'])
  16. if isinstance(output_data, dict) and 'output' in output_data:
  17. output_array = orjson.loads(output_data['output'])
  18. else:
  19. raise ValueError("Invalid data structure: 'output' not found in data")
  20. else:
  21. raise ValueError("Invalid data structure: 'data' not found in root")
  22. # Create a list to store the extracted fields
  23. results = []
  24. # Extract required fields from each item
  25. for item in output_array:
  26. result = {
  27. '需求钩子出现时间': item.get('需求钩子出现时间', ''),
  28. '需求详细query': item.get('需求详细query', ''),
  29. '需求钩子话术': item.get('需求钩子话术', '')
  30. }
  31. results.append(result)
  32. # Create DataFrame
  33. df = pd.DataFrame(results)
  34. # Write to Excel
  35. output_file = 'trigger_result.xlsx'
  36. df.to_excel(output_file, index=False)
  37. print(f"Successfully wrote {len(results)} records to {output_file}")
  38. except Exception as e:
  39. print(f"Error processing trigger results: {str(e)}")
  40. raise
  41. def process_file(input_file):
  42. """
  43. Process a file containing JSON data and write results to Excel.
  44. Args:
  45. input_file (str): Path to the input file containing JSON data
  46. """
  47. try:
  48. # Read the input file
  49. with open(input_file, 'r', encoding='utf-8') as f:
  50. json_data = f.read()
  51. # Process the data
  52. process_trigger_results(json_data)
  53. except Exception as e:
  54. print(f"Error processing file {input_file}: {str(e)}")
  55. raise
  56. if __name__ == '__main__':
  57. # Example usage
  58. input_file = 'trigger_response.json' # Replace with your input file path
  59. if os.path.exists(input_file):
  60. process_file(input_file)
  61. else:
  62. print(f"Input file {input_file} not found")