gpt4 book ai didi

linux - 在 Linux 中解析 CSV 文件并执行转换

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:39:32 24 4
gpt4 key购买 nike

我有一个包含很多列的大 CSV 文件(数百 MB):

1;18Jun2013;23:58:58;;;l;o;t;s;;;;o;f;;;;;o;t;h;e;r;;;;;c;o;l;u;m;n;s;;;;;

您看到第二列是一个日期,我希望采用 %Y-%m-%d 格式以便在数据库中轻松插入和排序。我相信转换原始数据比稍后在数据库中更容易和更快。

主脚本使用 bash。现在,我已按以下方式进行转换:

  sed -n '2,$p' $TMPF | while read line; do
begin=$(echo "$line" | cut -d\; -f1)
origdate=$(echo "$line" | cut -d\; -f2)
#cache date translations, hash table for the poor
eval origdateh=h$origdate
if [ "x${!origdateh}" = "x" ]; then
# not cached till now, need to call date, then store
datex=$(date -d "$origdate" +%Y-%m-%d)
eval h$origdate="$datex"
else
# cache hit
datex=$(eval echo \$h$origdate)
fi
end=$(echo "$line" | cut -d\; -f3-)
echo "$begin;$datex;$end" >> $TMPF2
done

我使用 sed 从第二行开始(第一行包含 CSV 标题),我相信所有带有回声和剪切的子 shell 都会减慢速度,所以“哈希表”真的没有多大用处......

谁能让这一切变得快速?

最佳答案

不要使用 bash 脚本,而是使用 Python 脚本。至少,这将更具可读性/可维护性并且可能更高效。

示例代码可能如下所示(未经测试):

# file: converter.py

import datetime

def convert_line(line):
# split line on ';'
line = line.split(';')
# get the date part (second column)
# parse date from string
date = datetime.date.strptime(line[1], '%d%a%Y')
# convert to desired format
# replace item in line
line[1] = date.strftime('%Y-%m-%d')
# return converted line
return ';'.join(line)

while True:
print convert_line(raw_input())

现在你只需要做:

cat file.csv | python converter.py > file_converted.csv

替代实现:

# file: converter_2.py

import datetime

def convert_line(line):
# split line on ';'
line = line.split(';')
# get the date part (second column)
# parse date from string
date = datetime.date.strptime(line[1], '%d%a%Y')
# convert to desired format
# replace item in line
line[1] = date.strftime('%Y-%m-%d')
# return converted line
return ';'.join(line)

with open('file.csv') as infile, open('file_converted.csv', 'w+') as outfile:
outfile.writelines(convert_line(line) for line in infile)

示例用法:

python converter_2.py

如果您的 csv 中有一些标题行,当然不能使用此函数转换它们。

关于linux - 在 Linux 中解析 CSV 文件并执行转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17244920/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com