gpt4 book ai didi

python - 如何使用 Python 解析某些 .csv 行? (包含示例文件)

转载 作者:行者123 更新时间:2023-12-01 04:06:01 26 4
gpt4 key购买 nike

我掌握了解析 .csv 文件并将某些行放入列表和/或字典中的基础知识,但我无法破解这个。

有 9 行包含一般信息,例如

  • 客户名称
  • 发票号码
  • 发票日期
  • ...等等

然后是产品和价格的详细列表。我想做的是:

  1. 从前 9 行获取“发票编号”、“签发日期”、“到期日期”和“到期金额”
  2. 仅从剩余行中获取“描述”和“金额”

进入字典。然后我会将这些数据写入 mySql 数据库。有人可以建议我如何在这个“标题”(第 9 行)之后开始将项目添加到字典中吗?

谢谢。

ExampleCSV :

Bill to Client                          
Billing ID xxxx-xxxx-xxxx
Invoice number 3359680287
Issue date 1/31/2016
Due Date 3/1/2016
Currency EUR
Invoice subtotal 2,762,358.40
VAT (0%) 0
Amount due 2,762,358.40

Account ID Account Order Purchase Order Product Description Quantity Units Amount
xxx-xxx-xxxx Client - Search, GDN, Youtube Client- Google Search Google AdWords Belgium_GDN_january_(FR) 1 Impressions 0.04
xxx-xxx-xxxx Client - Search, GDN, Youtube Client- Google Search Google AdWords UK_GDN_january 392 Impressions 2.92
xxx-xxx-xxxx Client - Search, GDN, Youtube Client- Google Search Google AdWords Poland_GDN_january 12 Impressions 0.05

xxx-xxx-xxxx Client - Search, GDN, Youtube Client Google AdWords Switzerland Family vacation 251 Clicks 4,718.91
xxx-xxx-xxxx Client - Search, GDN, Youtube Client Google
xxx-xxx-xxxx Client - Search, GDN, Youtube Client Google AdWords Invalid activity -16.46

当我尝试这段代码时:

import csv

with open('test.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter=",")
for row in readCSV:
print(row[0])

我在终端中得到这个:

Bill to
Billing ID
Invoice number
Issue date
Due Date
Currency Invoice
subtotal
VAT (0%)
Amount due
Traceback (most recent call last): File "xlwings_test.py", line 7, in print(row[0]) IndexError: list index out of range xlwings git:master ❯

最佳答案

您可以使用csv模块和enumerate读者对象。

import csv

dict1 = {}
dict2 = {}

with open("test.csv", "rb") as f:
reader = csv.reader(f, delimiter="\t")
for i, line in enumerate(reader):
if i in [3, 4, 5, 9]:
prop_name = line[0]
prop_val = line[1]
dict1[prop_name] = prop_value # Invoice number, Issue date, Due date or Amount date
elif i > 11:
# Fetch other information like 'description' and 'amount'
print "Description: " + line[5]
print "Amount: " + line[-1]
dict2[line[5]] = line[-1]

print dict1
print dict2

关于python - 如何使用 Python 解析某些 .csv 行? (包含示例文件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35562224/

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