process_data.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. import csv
  2. import chardet
  3. import sys
  4. import logging
  5. from pathlib import Path
  6. from mylib.translate_utils import insert_empty_columns, process_batch_translations
  7. from brand_add_url_link import create_hyperlink, create_asin_link
  8. from mylib.logging_config import setup_logging
  9. # Setup custom logging
  10. setup_logging()
  11. logger = logging.getLogger(__name__)
  12. def detect_encoding(file_path):
  13. try:
  14. with open(file_path, 'rb') as f:
  15. raw_data = f.read()
  16. result = chardet.detect(raw_data)
  17. return result['encoding']
  18. except Exception as e:
  19. logger.error(f"Error detecting encoding for {file_path}: {e}")
  20. sys.exit(1)
  21. def read_csv(file_path):
  22. encodings_to_try = ['utf-8-sig', 'gb18030', 'shift_jis', 'euc-jp']
  23. detected_encoding = detect_encoding(file_path)
  24. logger.info(f"Detected encoding: {detected_encoding}")
  25. if detected_encoding:
  26. encodings_to_try.insert(0, detected_encoding)
  27. for encoding in encodings_to_try:
  28. try:
  29. with open(file_path, 'r', encoding=encoding) as f:
  30. reader = csv.reader(f)
  31. return list(reader)
  32. except UnicodeDecodeError:
  33. continue
  34. except Exception as e:
  35. logger.error(f"Error with encoding {encoding}: {e}")
  36. continue
  37. logger.error("Failed to read file with all attempted encodings")
  38. sys.exit(1)
  39. def add_brand_asin_links(data, brand_indices, asin_indices):
  40. """为品牌和ASIN列添加链接"""
  41. try:
  42. for row in data[2:]: # 从第三行开始处理
  43. # 处理品牌列
  44. for index in brand_indices:
  45. if index < len(row) and row[index]:
  46. row[index] = create_hyperlink(row[index], 'https://www.amazon.co.jp/s?k=')
  47. # 处理ASIN列
  48. for index in asin_indices:
  49. if index < len(row) and row[index]:
  50. row[index] = create_asin_link(row[index])
  51. return data
  52. except Exception as e:
  53. logger.error(f"Error adding brand/ASIN links: {e}")
  54. sys.exit(1)
  55. def save_csv(data, file_path):
  56. try:
  57. with open(file_path, 'w', encoding='utf-8-sig', newline='') as f:
  58. writer = csv.writer(f)
  59. writer.writerows(data)
  60. except Exception as e:
  61. logger.error(f"Error saving CSV to {file_path}: {e}")
  62. sys.exit(1)
  63. def main(input_file, output_file):
  64. try:
  65. # Read CSV with proper encoding
  66. data = read_csv(input_file)
  67. # 定义需要处理的列索引
  68. search_term_index = 1 # 搜索词列
  69. brand_indices = [2, 3, 4] # 品牌列
  70. asin_indices = [7, 11, 15] # ASIN列
  71. category_indices = [5, 6, 7] # 类别列
  72. # 插入空列用于翻译
  73. insert_indices = [search_term_index] + category_indices
  74. data = insert_empty_columns(data, insert_indices)
  75. # 更新标题行
  76. data[0][search_term_index + 1] = "中文翻译"
  77. for index in category_indices:
  78. data[0].insert(index + 1, "中文翻译")
  79. # 处理翻译
  80. data = process_batch_translations(data, search_term_index, category_indices)
  81. # 添加品牌和ASIN链接
  82. data = add_brand_asin_links(data, brand_indices, asin_indices)
  83. # 保存处理后的数据
  84. save_csv(data, output_file)
  85. logger.info(f"Successfully processed and saved to {output_file}")
  86. except Exception as e:
  87. logger.error(f"Error processing file: {e}")
  88. sys.exit(1)
  89. if __name__ == "__main__":
  90. output_dir = Path('temp')
  91. input_file = output_dir/"测试.csv"
  92. output_file = output_dir/"processed_测试.csv"
  93. main(input_file, output_file)