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

如何使用Groovy获取CSV文件中某条记录的相邻值

无需外部库,从CSV中获取特定条目的相邻值

绝对没问题!完全不用依赖任何第三方CSV库,用原生的字符串处理就能轻松搞定这个需求。我给你捋清楚思路,再附上实用的代码示例:

核心实现逻辑

不管用什么编程语言,核心步骤都是这几步:

  • 把CSV内容按行拆分,逐行处理
  • 每行拆分成独立的单元格(注意CSV的分隔符,通常是逗号)
  • 遍历单元格找到目标条目(比如"upsert")的位置
  • 根据需求提取它的相邻值(左边或右边)

Python 原生实现示例

这个例子假设你的CSV用逗号分隔,且单元格没有包含逗号或引号的复杂内容(如果有这类场景,我后面会补充说明):

def fetch_adjacent_value(csv_content, target_item, direction="right"):
    # 先把CSV内容按行分割,去掉首尾空白行
    rows = [row.strip() for row in csv_content.strip().split('\n') if row.strip()]
    
    for row in rows:
        # 拆分当前行的单元格
        cells = [cell.strip() for cell in row.split(',')]
        try:
            # 找到目标条目的索引
            target_index = cells.index(target_item)
            # 根据方向获取相邻值
            if direction == "right" and target_index + 1 < len(cells):
                return cells[target_index + 1]
            elif direction == "left" and target_index - 1 >= 0:
                return cells[target_index - 1]
        except ValueError:
            # 当前行没有目标条目,继续下一行
            continue
    # 遍历完所有行都没找到目标
    return None

# 测试用例
if __name__ == "__main__":
    # 模拟从文件读取的CSV内容(实际用open()读取本地文件即可)
    sample_csv = """
    operation,count
    insert,100
    upsert,50
    delete,30
    """
    # 获取"upsert"右侧的值
    result = fetch_adjacent_value(sample_csv, "upsert")
    print(result)  # 输出: 50

处理复杂CSV格式的小技巧

如果你的CSV存在单元格包含逗号、换行或者被引号包裹的情况(比如"Doe, John",30),可以手动扩展拆分逻辑:

  • 遍历字符串时,跟踪是否处于引号内部
  • 只有当不在引号内时,才用逗号拆分单元格

Java 原生实现示例(可选)

如果用Java,思路完全一致,用原生的文件读取和字符串处理:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

public class CSVAdjacentValueFinder {
    public static String getAdjacentValue(String csvPath, String target, String direction) throws IOException {
        // 读取CSV所有行
        List<String> lines = Files.readAllLines(Paths.get(csvPath));
        
        for (String line : lines) {
            String[] cells = line.split(",");
            for (int i = 0; i < cells.length; i++) {
                String cell = cells[i].trim();
                if (cell.equals(target)) {
                    if ("right".equals(direction) && i + 1 < cells.length) {
                        return cells[i+1].trim();
                    } else if ("left".equals(direction) && i - 1 >= 0) {
                        return cells[i-1].trim();
                    }
                }
            }
        }
        return null;
    }

    public static void main(String[] args) throws IOException {
        String result = getAdjacentValue("sample.csv", "upsert", "right");
        System.out.println(result); // 输出: 50
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:49:20