You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将XLS文件处理代码适配为TXT文件输入的示例代码请求

替代XLS的WASDE数据TXT处理代码

问题背景

原有针对WASDE XLS文件的Python处理代码因文件格式不一致无法稳定运行,改用同内容的TXT文件可解决该问题,以下是实现相同功能的TXT处理代码及注意事项。

原XLS处理代码(参考)

import pandas as pd
import glob
import re

# Step 1: Find the first wasde file
files = glob.glob("WASDE*.xls")
if not files:
    raise FileNotFoundError("No .xls file starting with 'wasde' found.")
file_path = files[0]

# Step 2: Read sheet, grabbing row headers
sheet_name = "Page 12"
df = pd.read_excel(file_path, sheet_name=sheet_name, header=None)

# Step 3: Slice rows 33-49 (Excel indexing → pandas is 0-based)
df = df.iloc[32:49, :]

# Drop completely empty columns
df = df.dropna(axis=1, how="all")

# Step 4: Get header row (Excel row 9 → pandas row index 8)
header_row = pd.read_excel(file_path, sheet_name=sheet_name, header=None).iloc[8]

# Build new column names
new_columns = ["CORN Supply-Use"]
new_columns.append(str(header_row.iloc[1]))   # 2nd column
new_columns.append(str(header_row.iloc[2]))   # 3rd column
new_columns.append(str(header_row.iloc[3]) + " Prev")  # 4th col + "Prev"
new_columns.append(str(header_row.iloc[4]) + " Curr")  # 5th col + "Curr"

df.columns = new_columns

# Step 5: Clean text in first column
df["CORN Supply-Use"] = (
    df["CORN Supply-Use"]
    .astype(str)
    .str.replace(r"\s*\d+/?\d*\s*$", "", regex=True)  # remove trailing footnote markers like "3/"
    .str.strip()
)
df = df.reset_index(drop=True).drop([2, 4], errors="ignore")

print(df)

TXT文件替代处理代码

import pandas as pd
import glob
import re

# Step 1: 查找WASDE开头的TXT文件
files = glob.glob("WASDE*.txt")
if not files:
    raise FileNotFoundError("未找到以'wasde'开头的.txt文件。")
file_path = files[0]

# Step 2: 读取TXT文件,定位到Page 12的内容
with open(file_path, 'r', encoding='utf-8') as f:
    lines = f.readlines()

# 找到Page 12的起始行
page_start = None
for idx, line in enumerate(lines):
    if "Page 12" in line:
        page_start = idx + 1  # 跳过Page标题行
        break
if not page_start:
    raise ValueError("未找到Page 12的内容。")

# Step 3: 截取对应原XLS的33-49行(TXT中Page12内的第32-48行)
target_lines = lines[page_start + 31 : page_start + 48]

# Step 4: 按固定宽度读取数据,匹配TXT格式的列分布
col_specs = [
    (0, 35),   # CORN Supply-Use列
    (35, 45),  # 第二列
    (45, 55),  # 第三列
    (55, 65),  # 第四列(Prev)
    (65, 75)   # 第五列(Curr)
]

df = pd.read_fwf(pd.compat.StringIO(''.join(target_lines)), colspecs=col_specs, header=None)

# 移除全空列
df = df.dropna(axis=1, how="all")

# Step 5: 构建列名,对应原XLS的表头逻辑
header_line = lines[page_start + 7].strip()
header_parts = re.split(r'\s{2,}', header_line)  # 按多空格拆分表头
new_columns = ["CORN Supply-Use"]
new_columns.append(header_parts[1])
new_columns.append(header_parts[2])
new_columns.append(header_parts[3] + " Prev")
new_columns.append(header_parts[4] + " Curr")

df.columns = new_columns

# Step 6: 清理第一列文本,移除末尾脚注标记
df["CORN Supply-Use"] = (
    df["CORN Supply-Use"]
    .astype(str)
    .str.replace(r"\s*\d+/?\d*\s*$", "", regex=True)
    .str.strip()
)

# 重置索引并删除指定行
df = df.reset_index(drop=True).drop([2, 4], errors="ignore")

print(df)

处理提示

  • 固定列宽调整:WASDE的TXT文件为固定宽度格式,若数据列位置偏移,需根据实际TXT内容修改col_specs中的数值,确保每列数据准确截取。
  • 页码定位兼容:若TXT中"Page 12"格式有变化(如大小写、空格差异),可改为if "PAGE 12" in line.upper()增强匹配兼容性。
  • 表头拆分适配:表头拆分依赖多空格分隔,若表头格式变化,可调整re.split(r'\s{2,}', header_line)的正则规则,保证表头项拆分正确。
  • 编码问题处理:若读取TXT出现乱码,可尝试将encoding='utf-8'替换为encoding='latin-1',适配USDA文件的常见编码。

内容的提问来源于stack exchange,提问作者prashanth manohar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.08 08:13:09