mrh пре 1 година
родитељ
комит
35a319aa0a
15 измењених фајлова са 204 додато и 293 уклоњено
  1. 3 0
      CONVENTIONS.md
  2. 1 0
      .aider.conf.yml
  3. 6 1
      .gitignore
  4. 0 108
      1.md
  5. 0 67
      1.py
  6. 0 0
      add_url_link.py
  7. 0 0
      docs/2.md
  8. 0 0
      docs/3.md
  9. 0 20
      excel.py
  10. 81 0
      pdfzh_translator.py
  11. 0 15
      taobao.py
  12. 96 0
      translate_new_col.py
  13. 17 0
      user_requiement_doc.md
  14. 0 48
      农作物.py
  15. 0 34
      小说.py

+ 3 - 0
CONVENTIONS.md

@@ -0,0 +1,3 @@
+编程注意事项:
+- 编写代码遵循模块化,高内聚低耦合原则,符合程序设计的基本原则。
+- 如果我有的任何提示和注意事项要说明在代码中,都应在代码中添加注释。

+ 1 - 0
.aider.conf.yml

@@ -0,0 +1 @@
+read: [CONVENTIONS.md, user_requiement_doc.md]

+ 6 - 1
.gitignore

@@ -1,4 +1,9 @@
 .venv
 *.xlsx
 *.csv
-.idea
+.idea
+testm
+temp
+__pycache__
+myenv
+env

+ 0 - 108
1.md

@@ -1,108 +0,0 @@
-# 导出的亚马逊表格处理
-
-当前目录: C:\python\WM
-
-python 环境: ./venv/bin/python
-
-```
-import csv
-
-
-def read_csv(file_path):
-    """
-    读取CSV文件并返回数据列表
-    :param file_path: CSV文件路径
-    :return: 包含CSV数据的列表
-    """
-    with open(file_path, mode='r', encoding='utf-8') as file:
-        reader = csv.reader(file)
-        data = [row for row in reader]
-    return data
-
-
-def insert_empty_column(data, column_index):
-    """
-    在指定列之后插入一个空列
-    :param data: CSV数据列表
-    :param column_index: 插入空列的列索引
-    :return: 插入空列后的数据列表
-    """
-    for row in data:
-        row.insert(column_index + 1, '')
-    return data
-
-
-def translate_text(text, target_language='zh'):
-    """
-    翻译文本(测试函数,返回固定文本)
-    :param text: 需要翻译的文本
-    :param target_language: 目标语言,默认为中文
-    :return: 翻译后的文本(测试文本)
-    """
-    # 这里我们使用一个固定的测试文本作为翻译结果
-    return "测试翻译文本"
-
-
-def translate_column(data, column_index, target_language='zh'):
-    """
-    翻译指定列的文本
-    :param data: CSV数据列表
-    :param column_index: 需要翻译的列索引
-    :param target_language: 目标语言,默认为中文
-    :return: 翻译后的数据列表
-    """
-    for row in data:
-        if len(row) > column_index:
-            row[column_index] = translate_text(row[column_index], target_language)
-    return data
-
-
-def save_csv(data, file_path):
-    """
-    将数据保存为CSV文件
-    :param data: 需要保存的数据列表
-    :param file_path: 保存的文件路径
-    """
-    with open(file_path, mode='w', newline='', encoding='utf-8') as file:
-        writer = csv.writer(file)
-        writer.writerows(data)
-
-
-def process_csv(input_file, output_file, column_index, target_language='zh'):
-    """
-    处理CSV文件的主要函数
-    :param input_file: 输入的CSV文件路径
-    :param output_file: 输出的CSV文件路径
-    :param column_index: 需要插入空列的列索引
-    :param target_language: 目标语言,默认为中文
-    """
-    # 读取CSV文件
-    data = read_csv(input_file)
-
-    # 插入空列
-    data = insert_empty_column(data, column_index)
-
-    # 翻译第二列的文本
-    data = translate_column(data, column_index, target_language)
-
-    # 保存为新文件
-    save_csv(data, output_file)
-
-
-# 测试代码
-if __name__ == "__main__":
-    input_file = "C:\\Users\\74262\\Desktop\\excel\\18.JP家具.csv"
-    output_file = "C:\\Users\\74262\\Desktop\\excel\\18.JP家具_processed.csv"
-    column_index = 2  # 插入空列的列索引(第2列)
-
-    process_csv(input_file, output_file, column_index)
-```
-编码规范:
-- 要求每个要求都要模块化处理,遵循高内聚、低耦合编码规范,用函数封装,最小化封装的代码量。
-
-实现功能:
-1. 表格文件: "C:\Users\74262\Desktop\excel\18.JP家具.csv"
-2. 将表格第N列往右插入一空列。N是传参,测试代码为第2列。但不要修改原文件,保存为另一个文件
-3. 将第N列中的文字,翻译成另一种语言,默认中文。保存到 column_index +1 列中,允许指定从 哪一行开始翻译,测试从第二行。翻译使用一个函数封装,暂不使用翻译器,代码使用一个测试文本作为翻译结果。
-
-完成步骤3

+ 0 - 67
1.py

@@ -1,67 +0,0 @@
-import csv
-
-def read_csv(file_path):
-    """读取CSV文件并返回数据列表"""
-    with open(file_path, mode='r', encoding='utf-8') as file:
-        reader = csv.reader(file)
-        data = [row for row in reader]
-    return data
-
-
-def insert_empty_column(data, column_index):
-    """在指定列之后插入一个空列"""
-    for row in data:
-        row.insert(column_index + 1, '')  # 插入在目标列后面
-    return data
-
-
-def translate_text(text, target_language='zh'):
-    """翻译文本(测试函数,返回固定文本)"""
-
-    return text + "测试翻译文本"  # 测试用的固定文本
-
-
-def translate_column(data, column_index, start_row=0, target_language='zh'):
-    """
-    翻译指定列的文本,并将结果保存到下一列
-    :param data: CSV数据列表
-    :param column_index: 需要翻译的列索引
-    :param start_row: 开始翻译的行索引,默认为第0行
-    :param target_language: 目标语言,默认为中文
-    :return: 翻译后的数据列表
-    """
-    for i, row in enumerate(data[start_row:], start=start_row):
-        if len(row) > column_index:
-            translated_text = translate_text(row[column_index], target_language)
-            row[column_index + 1] = translated_text  # 写入到下一列
-    return data
-
-
-def save_csv(data, file_path):
-    """将数据保存为CSV文件"""
-    with open(file_path, mode='w', newline='', encoding='utf-8') as file:
-        writer = csv.writer(file)
-        writer.writerows(data)
-
-
-def process_csv(input_file, output_file, column_index, start_row=0, target_language='zh'):
-    """处理CSV文件的主要函数"""
-    data = read_csv(input_file)
-
-    # 插入空列
-    data = insert_empty_column(data, column_index)
-
-    # 翻译第二列的文本并保存到下一列
-    data = translate_column(data, column_index, start_row, target_language)
-
-    # 保存为新文件
-    save_csv(data, output_file)
-
-
-if __name__ == "__main__":
-    input_file = "C:\\Users\\74262\\Desktop\\excel\\18.JP家具.csv"
-    output_file = "C:\\Users\\74262\\Desktop\\excel\\18.JP家具_processed.csv"
-    column_index = 1  # 插入空列的列索引(第2列)
-    start_row = 2  # 从第2行开始翻译(通常第0行是标题)
-
-    process_csv(input_file, output_file, column_index, start_row)

+ 0 - 0
2.py → add_url_link.py


+ 0 - 0
2.md → docs/2.md


+ 0 - 0
3.md → docs/3.md


+ 0 - 20
excel.py

@@ -1,20 +0,0 @@
-import pandas as pd
-
-# 创建一个字典,包含一些数据
-data = {
-    '姓名': ['张三', '李四', '王五'],
-    '年龄': [28, 34, 29],
-    '城市': ['北京', '上海', '广州']
-}
-
-# 使用字典创建DataFrame
-df = pd.DataFrame(data)
-
-# 打印DataFrame
-print(df)
-
-# 将DataFrame保存为Excel文件
-file_path = 'example.xlsx'
-df.to_excel(file_path, index=False)
-
-print(f"Excel文件已保存到 {file_path}")

+ 81 - 0
pdfzh_translator.py

@@ -0,0 +1,81 @@
+# 改编自: https://github.com/Byaidu/PDFMathTranslate/blob/main/pdf2zh/translator.py
+import html
+import logging
+import os
+import re
+from json import dumps, loads
+
+import openai
+import requests
+
+
+class BaseTranslator:
+    def __init__(self, service, lang_out, lang_in, model):
+        self.service = service
+        self.lang_out = lang_out
+        self.lang_in = lang_in
+        self.model = model
+
+    def translate(self, text) -> str: ...  # noqa: E704
+
+    def __str__(self):
+        return f"{self.service} {self.lang_out} {self.lang_in}"
+
+
+class GoogleTranslator(BaseTranslator):
+    def __init__(self, service, lang_out, lang_in, model):
+        lang_out = "zh-CN" if lang_out == "auto" else lang_out
+        lang_in = "en" if lang_in == "auto" else lang_in
+        super().__init__(service, lang_out, lang_in, model)
+        self.session = requests.Session()
+        self.base_link = "http://translate.google.com/m"
+        self.headers = {
+            "User-Agent": "Mozilla/4.0 (compatible;MSIE 6.0;Windows NT 5.1;SV1;.NET CLR 1.1.4322;.NET CLR 2.0.50727;.NET CLR 3.0.04506.30)"  # noqa: E501
+        }
+
+    def translate(self, text):
+        text = text[:5000]  # google translate max length
+        response = self.session.get(
+            self.base_link,
+            params={"tl": self.lang_out, "sl": self.lang_in, "q": text},
+            headers=self.headers,
+        )
+        re_result = re.findall(
+            r'(?s)class="(?:t0|result-container)">(.*?)<', response.text
+        )
+        if response.status_code == 400:
+            result = "IRREPARABLE TRANSLATION ERROR"
+        elif len(re_result) == 0:
+            raise ValueError("Empty translation result")
+        else:
+            result = html.unescape(re_result[0])
+        return result
+
+
+class OpenAITranslator(BaseTranslator):
+    def __init__(self, service, lang_out, lang_in, model):
+        lang_out = "zh-CN" if lang_out == "auto" else lang_out
+        lang_in = "en" if lang_in == "auto" else lang_in
+        super().__init__(service, lang_out, lang_in, model)
+        self.options = {"temperature": 0}  # 随机采样可能会打断公式标记
+        # OPENAI_BASE_URL
+        # OPENAI_API_KEY
+        self.client = openai.OpenAI()
+
+    def translate(self, text) -> str:
+        response = self.client.chat.completions.create(
+            model=self.model,
+            **self.options,
+            messages=[
+                {
+                    "role": "system",
+                    "content": "You are a professional,authentic machine translation engine.",
+                },
+                {
+                    "role": "user",
+                    "content": f"Translate the following markdown source text to {self.lang_out}. Keep the formula notation $v*$ unchanged. Output translation directly without any additional text.\nSource Text: {text}\nTranslated Text:",  # noqa: E501
+                },
+            ],
+        )
+        return response.choices[0].message.content.strip()
+

+ 0 - 15
taobao.py

@@ -1,15 +0,0 @@
-from DrissionPage import Chromium
-
-# 启动或接管浏览器,并创建标签页对象
-tab = Chromium().latest_tab
-# 跳转到登录页面
-tab.get('https://gitee.com/login')
-
-# 定位到账号文本框,获取文本框元素
-ele = tab.ele('#user_login')
-# 输入对文本框输入账号
-ele.input('123dgdsa1gds5')
-# 定位到密码文本框并输入密码
-tab.ele('#user_password').input('谢谢烦烦烦ccc')
-# 点击登录按钮
-#tab.ele('@value=登 录').click()

+ 96 - 0
translate_new_col.py

@@ -0,0 +1,96 @@
+import os
+import csv
+from ai_trans import translate_sentences
+
+# 设置 OpenAI API 配置
+os.environ['OPENAI_API_KEY'] = 'sk-NscqaCD1PfVm7soEF3C3E6297bE14d7fB595Be8f17F39aFf'
+os.environ['OPENAI_API_BASE'] = 'https://aiapi.magong.site/v1'
+
+def read_csv(file_path):
+    """读取CSV文件并返回数据列表"""
+    encodings = ['utf-8', 'latin-1', 'gbk']
+    for encoding in encodings:
+        try:
+            with open(file_path, mode='r', encoding=encoding) as file:
+                reader = csv.reader(file)
+                data = [row for row in reader]
+            return data
+        except UnicodeDecodeError:
+            continue
+        except Exception as e:
+            print(f"Error reading CSV file with encoding {encoding}: {e}")
+            return []
+    print("Failed to read CSV file with any of the specified encodings.")
+    return []
+
+
+def insert_empty_column(data, column_index):
+    """在指定列之后插入一个空列"""
+    for row in data:
+        row.insert(column_index + 1, '')  # 插入在目标列后面
+    return data
+
+
+
+
+
+def translate_column(data, column_index, start_row=0, target_language='zh'):
+    """
+    翻译指定列的文本,并将结果保存到下一列
+    :param data: CSV数据列表
+    :param column_index: 需要翻译的列索引
+    :param start_row: 开始翻译的行索引,默认为第0行
+    :param target_language: 目标语言,默认为中文
+    :return: 翻译后的数据列表
+    """
+    sentences_to_translate = [row[column_index] for i, row in enumerate(data[start_row:], start=start_row) if len(row) > column_index]
+    
+    if sentences_to_translate:
+        try:
+            print(f"Translating {len(sentences_to_translate)} sentences to {target_language}.")
+            print(f"Input sentences: {sentences_to_translate}")
+            translated_output = translate_sentences(sentences_to_translate, target_language, api_key='YOUR_API_KEY')
+            print(f"Translated output: {translated_output}")
+            translations = translated_output.get("translations", [])
+            
+            for i, row in enumerate(data[start_row:], start=start_row):
+                if len(row) > column_index and i - start_row < len(translations):
+                    row[column_index + 1] = translations[i - start_row]  # 写入到下一列
+                    print(f"Translated row {i}: {row[column_index]} -> {row[column_index + 1]}")
+        except Exception as e:
+            print(f"Error translating rows: {e}")
+    
+    return data
+
+
+def save_csv(data, file_path):
+    """将数据保存为CSV文件"""
+    try:
+        with open(file_path, mode='w', newline='', encoding='utf-8') as file:
+            writer = csv.writer(file)
+            writer.writerows(data)
+    except Exception as e:
+        print(f"Error saving CSV file: {e}")
+
+
+def process_csv(input_file, output_file, column_index, start_row=0, target_language='zh'):
+    """处理CSV文件的主要函数"""
+    data = read_csv(input_file)
+
+    # 插入空列
+    data = insert_empty_column(data, column_index)
+
+    # 翻译第二列的文本并保存到下一列
+    data = translate_column(data, column_index, start_row, target_language)
+
+    # 保存为新文件
+    save_csv(data, output_file)
+
+
+if __name__ == "__main__":
+    input_file = "18.JP家具 - 小的.csv"
+    output_file = "18.JP家具 - 小的_processed.csv"
+    column_index = 1  # 插入空列的列索引(第2列)
+    start_row = 2  # 从第2行开始翻译(通常第0行是标题)
+
+    process_csv(input_file, output_file, column_index, start_row)

+ 17 - 0
user_requiement_doc.md

@@ -0,0 +1,17 @@
+## 项目说明:
+这是一个 Excel 表格处理的项目,用 python 脚本完成客户对文档的要求。
+
+## 表格:
+导出了 amazone 的表格,第一列不是标题,而是一些说明信息:
+报告范围=["每季度"]	选择年份=["2024"]	选择季度=["3"]	点击最高的品类=["Lawn and Garden"]			
+
+第二列开始才是标题和正文,例如:
+搜索频率排名	搜索词	点击量最高的品牌 #1	点击量最高的品牌 #2	点击量最高的品牌 #3	点击量最高的类别 #1
+120	プール	Ameer	Intex	INTEX	Toys
+229	テント	Coleman	Kaitou	PYKES PEAK	Sports
+
+
+## 用户需求:
+
+1. 在搜索词列的右边插入一列,在新一列中翻译成中文
+2. 在搜索词列点击单元格内容,可以直接跳转到亚马逊链接,网页是搜索词的搜索内容

+ 0 - 48
农作物.py

@@ -1,48 +0,0 @@
-import pandas as pd
-
-# 定义生成含量数据的函数
-def generate_content(layer):
-    """
-    根据土层深度生成硝态氮和铵态氮的含量数据。
-
-    参数:
-    layer (str): 土层名称,格式为 "start-endcm",例如 "0-10cm"。
-
-    返回:
-    float: 生成的含量数据,保留两位小数。
-    """
-    # 去除 "cm" 单位并转换为整数
-    layer_depth = int(layer.split('-')[-1].replace('cm', ''))
-
-    if layer_depth < 40:
-        start_concentration = 25
-        increment = -0.554
-    elif layer_depth < 80:
-        start_concentration = 6
-        increment = 0.554
-    elif layer_depth < 100:
-        start_concentration = 25
-        increment = max(-0.554, (6 - start_concentration) / (100 - layer_depth))
-    else:
-        start_concentration = 0
-        # raise ValueError("Layer depth must be between 0 and 100 cm")
-    concentration = round(start_concentration + increment * layer_depth, 2)
-    return concentration
-
-# 初始化数据列表
-data = []
-
-# 生成六个处理的数据
-for treatment in range(1, 7):
-    for layer in range(1, 11):
-        layer_name = f'{(layer - 1) * 10}-{layer * 10}cm'
-        nitrate_nitrogen = generate_content(layer_name)
-        ammonium_nitrogen = generate_content(layer_name)
-        data.append([layer_name, treatment, nitrate_nitrogen, ammonium_nitrogen])
-
-# 创建DataFrame
-df = pd.DataFrame(data, columns=['土层', '处理', '硝态氮', '铵态氮'])
-
-# 保存为xlsx文件
-# df.to_excel('/mnt/模拟土壤氮含量数据.xlsx', index=False)
-df.to_excel('./模拟土壤氮含量数据.xlsx', index=False)

+ 0 - 34
小说.py

@@ -1,34 +0,0 @@
-#爬取起点小说网的小说名称和作者
-
-#导入requests库
-from tkinter.font import names
-
-import requests
-from lxml import etree   #解析(提取)数据
-import openpyxl     #读写excel文件  pip stall openpyxl
-#模拟浏览器发送请求ulr
-url="https://fanqienovel.com/?force_mobile=1 "
-#伪装浏览器
-headers={'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0'}
-resp=requests.get(url,headers=headers)
-#输入响应状态🐎   200 表示正常响应
-#print(resp.status_code)
-print(resp.text)
-e=etree.HTML(resp.text)
-names=e.xpath('')      #xpath 提取小说名称
-authors=e.xpath('')    #xpath 提取小说作者
-#print(names)
-#print(authors)
-#整合数据,将两个列表中的内容整合到一个大列表中,大列表中有N多个小列表 格式['万赖之劫','小王']
-lst=['小说名称','小说作者']
-for i in range(0,len(names)):
-    lst.append([names[i],authors[i]])
-'''for item in lst:
-    print(item)'''      #进行数据的整合
-workbook=openpyxl.Workbook()   #创建一个 excel文件
-sheet=workbook.active       #获取活动表  sheet页
-#sheet有一个方法,append(列表)可以添加一行数据
-for item in lst:
-    sheet.append(item)   #遍历  循环一次就向列表中添加一行数据
-#保存
-workbook.save('我的小说.xlsx')