Ying 11 ヶ月 前
コミット
04a31052eb
11 ファイル変更461 行追加0 行削除
  1. 4 0
      .gitignore
  2. 108 0
      1.md
  3. 67 0
      1.py
  4. 15 0
      2.md
  5. 54 0
      2.py
  6. 15 0
      3.md
  7. 81 0
      3.py
  8. 20 0
      excel.py
  9. 15 0
      taobao.py
  10. 48 0
      农作物.py
  11. 34 0
      小说.py

+ 4 - 0
.gitignore

@@ -0,0 +1,4 @@
+.venv
+*.xlsx
+*.csv
+.idea

+ 108 - 0
1.md

@@ -0,0 +1,108 @@
+# 导出的亚马逊表格处理
+
+当前目录: 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

+ 67 - 0
1.py

@@ -0,0 +1,67 @@
+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)

+ 15 - 0
2.md

@@ -0,0 +1,15 @@
+# 导出的亚马逊表格处理
+
+当前目录: C:\python\WM
+
+python 环境: ./venv/bin/python
+
+编码规范:
+- 要求每个要求都要模块化处理,遵循高内聚、低耦合编码规范,用函数封装,最小化封装的代码量。
+- 翻译使用一个函数封装,暂不使用翻译器,代码使用一个测试文本作为翻译结果。
+
+实现功能:
+1. 点击进去可以看到读品牌在亚马逊如的所以产品。也就是调用上述代码实现超链接。
+2. 添加一个参数可以指定从哪一行开始添加超链接
+3. 让超链接的格式变为蓝色下划线的样式。为什么 pandas 不会自动变成 Excel 软件里那样的超链接样式?
+

+ 54 - 0
2.py

@@ -0,0 +1,54 @@
+import csv
+from urllib.parse import quote
+
+def create_hyperlink(value, base_url):
+    """为给定的值创建亚马逊搜索页面的超链接"""
+    return f'=HYPERLINK("{base_url}{quote(value)}&__mk_zh_CN=%E4%BA%9A%E9%A9%BC%E9%80%8A%E7%BD%91%E7%AB%99", "{value}")'
+
+def process_row(row, indices, base_url):
+    """为指定索引的单元格添加超链接"""
+    for index in indices:
+        if index < len(row):  # 确保索引在范围内
+            row[index] = create_hyperlink(row[index], base_url)
+    return row
+
+def column_letter_to_index(col_letter):
+    """将Excel列字母转换为0基索引"""
+    return sum((ord(c) - ord('A') + 1) * (26 ** i) for i, c in enumerate(reversed(col_letter.upper()))) - 1
+
+def read_and_process_csv(input_file, output_file, columns_to_process, use_letters=False, base_url='', start_row=0):
+    """读取CSV文件并处理指定列的数据,然后写入新文件"""
+    with open(input_file, 'r', encoding='utf-8', errors='ignore') as csvfile, \
+            open(output_file, 'w', newline='', encoding='utf-8') as new_csvfile:
+
+        reader = csv.reader(csvfile)
+        writer = csv.writer(new_csvfile)
+        headers = next(reader)  # 读取标题行
+
+        # 写入标题行到新的CSV文件
+        writer.writerow(headers)
+
+        # 获取要处理的列的索引
+        if use_letters:  # 如果使用列字母
+            indices = [column_letter_to_index(col) for col in columns_to_process]
+        else:  # 如果使用列索引(假设从0开始)
+            indices = [int(col) for col in columns_to_process]
+
+        # 遍历每一行并处理
+        for i, row in enumerate(reader):
+            if i < start_row:
+                writer.writerow(row)  # 直接写入未处理的行
+            else:
+                processed_row = process_row(row, indices, base_url)
+                writer.writerow(processed_row)
+
+# 定义要处理的CSV文件路径、输出文件路径以及需要添加超链接的列索引或列字母和亚马逊搜索的基础URL
+input_csv_path = 'C:\\Users\\74262\\Desktop\\excel\\18.JP家具.csv'
+output_csv_path = 'C:\\Users\\74262\\Desktop\\excel\\18.JP家具_processed.csv'
+columns_to_process = ['C', 'D', 'E']  # 使用列字母
+use_letters = True  # 是否使用列字母代替索引
+amazon_search_base_url = 'https://www.amazon.co.jp/s?k='
+start_row = 1  # 从第2行开始处理(索引从0开始)
+
+# 执行CSV处理
+read_and_process_csv(input_csv_path, output_csv_path, columns_to_process, use_letters, amazon_search_base_url, start_row)

+ 15 - 0
3.md

@@ -0,0 +1,15 @@
+# 导出的亚马逊表格处理
+
+当前目录: C:\python\WM
+
+python 环境: ./venv/bin/python
+
+编码规范:
+- 要求每个要求都要模块化处理,遵循高内聚、低耦合编码规范,用函数封装,最小化封装的代码量。
+- 翻译使用一个函数封装,暂不使用翻译器,代码使用一个测试文本作为翻译结果。
+- 不要修改原文件,需保存为另一个文件。input_file = 'C:\\Users\\74262\\Desktop\\excel\\18.JP家具.csv'  。 output_file = 'C:\\Users\\74262\\Desktop\\excel\\18.JP家具_processed.csv'  # Replace with your desired output file path
+
+
+实现功能:
+1. 导入一个表格,按关键词搜索表格中的标题所在列,翻译该列除标题以外的每一行内容,默认中文。
+

+ 81 - 0
3.py

@@ -0,0 +1,81 @@
+import pandas as pd
+
+# 定义文件路径和标题行位置
+INPUT_FILE_PATH = 'C:\\Users\\74262\\Desktop\\excel\\18.JP家具.csv'  # Replace with your actual file path
+OUTPUT_FILE_PATH = 'C:\\Users\\74262\\Desktop\\excel\\18.JP家具_processed.csv'  # Replace with your desired output file path
+HEADER_ROW = 1  # 标题行位置,默认为第一行(索引从0开始)
+
+
+def load_data(file_path, header_row):
+    """加载数据表,并根据指定行作为标题"""
+    try:
+        if file_path.endswith('.csv'):
+            df = pd.read_csv(file_path, header=header_row)
+        elif file_path.endswith(('.xls', '.xlsx')):
+            df = pd.read_excel(file_path, header=header_row)
+        else:
+            raise ValueError("Unsupported file format.")
+        return df
+    except Exception as e:
+        print(f"Failed to load data from {file_path}. Error: {e}")
+        return None
+
+
+def find_keyword_columns(df, keyword):
+    """查找包含关键词的列"""
+    keyword_columns = [col for col in df.columns if keyword.lower() in str(col).lower()]
+    return keyword_columns
+
+
+def mock_translate(text):
+    """模拟翻译函数,返回测试文本"""
+    return f"{text} (translated)"
+
+
+def translate_column(df, column_name):
+    """翻译指定列的内容"""
+    df[column_name] = df[column_name].apply(lambda x: mock_translate(x) if isinstance(x, str) else x)
+    return df
+
+
+def process_and_save(df, output_file_path):
+    """处理并保存数据到新文件"""
+    try:
+        if output_file_path.endswith('.csv'):
+            df.to_csv(output_file_path, index=False)
+        elif output_file_path.endswith(('.xls', '.xlsx')):
+            df.to_excel(output_file_path, index=False)
+        else:
+            raise ValueError("Unsupported file format for saving.")
+        print(f"Translated table saved to {output_file_path}")
+    except Exception as e:
+        print(f"Failed to save data to {output_file_path}. Error: {e}")
+
+
+def main():
+    # 加载数据
+    df = load_data(INPUT_FILE_PATH, HEADER_ROW)
+    if df is None:
+        return
+
+    # 查找包含关键词的列
+    keyword = "类别"  # 替换为实际的关键词
+    keyword_columns = find_keyword_columns(df, keyword)
+
+    if not keyword_columns:
+        print("No columns found with the specified keyword.")
+        return
+
+    print(f"Found columns: {keyword_columns}")
+
+    # 翻译找到的列
+    for column in keyword_columns:
+        print(f"Translating column: {column}")
+        df = translate_column(df, column)
+
+    # 保存处理后的数据到新的文件
+    process_and_save(df, OUTPUT_FILE_PATH)
+
+
+if __name__ == "__main__":
+    main()

+ 20 - 0
excel.py

@@ -0,0 +1,20 @@
+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}")

+ 15 - 0
taobao.py

@@ -0,0 +1,15 @@
+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()

+ 48 - 0
农作物.py

@@ -0,0 +1,48 @@
+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)

+ 34 - 0
小说.py

@@ -0,0 +1,34 @@
+#爬取起点小说网的小说名称和作者
+
+#导入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')