gpt4 book ai didi

python - 在 CSV 文件中搜索特定值的单个列并返回整行

转载 作者:行者123 更新时间:2023-11-28 17:50:50 24 4
gpt4 key购买 nike

问题

代码没有正确识别输入(项目)。它只是转储到我的失败消息,即使 CSV 文件中存在这样的值。谁能帮我确定我做错了什么?

背景

我正在开发一个小程序,它要求用户输入(此处未提供功能),搜索 CSV 文件(项目)中的特定列并返回整行。 CSV 数据格式如下所示。我已经缩短了实际数量的数据(49 个字段名称,18000 多行)。

代码

import csv
from collections import namedtuple
from contextlib import closing

def search():
item = 1000001
raw_data = 'active_sanitized.csv'
failure = 'No matching item could be found with that item code. Please try again.'
check = False

with closing(open(raw_data, newline='')) as open_data:
read_data = csv.DictReader(open_data, delimiter=';')
item_data = namedtuple('item_data', read_data.fieldnames)
while check == False:
for row in map(item_data._make, read_data):
if row.Item == item:
return row
else:
return failure

CSV 结构

active_sanitized.csv
Item;Name;Cost;Qty;Price;Description
1000001;Name here:1;1001;1;11;Item description here:1
1000002;Name here:2;1002;2;22;Item description here:2
1000003;Name here:3;1003;3;33;Item description here:3
1000004;Name here:4;1004;4;44;Item description here:4
1000005;Name here:5;1005;5;55;Item description here:5
1000006;Name here:6;1006;6;66;Item description here:6
1000007;Name here:7;1007;7;77;Item description here:7
1000008;Name here:8;1008;8;88;Item description here:8
1000009;Name here:9;1009;9;99;Item description here:9

注意事项

我使用 Python 的经验相对较少,但我认为这将是一个很好的开始,以便学习更多。

我确定了打开(并封装在一个关闭函数中)CSV 文件的方法,通过 DictReader 读取数据(以获取字段名称),然后创建一个命名元组以便能够快速选择所需的列输出(项目、成本、价格、名称)。列顺序很重要,因此使用 DictReader 和 namedtuple。

虽然可以对每个字段名称进行硬编码,但我觉得如果程序可以在文件打开时读取它们,那么在处理具有相同列名称但不同的类似文件时会更有帮助专栏组织。

研究

最佳答案

你遇到了三个问题:

  • 您在第一次失败时返回,因此它永远不会超过第一行。
  • 您正在从文件中读取字符串,并与 int 进行比较。
  • _make 迭代字典键,而不是值,产生错误的结果 (item_data(Item='Name', Name='Price', Cost='Qty ', Qty='Item', Price='Cost', Description='Description')).

    for row in (item_data(**data) for data in read_data):
    if row.Item == str(item):
    return row
    return failure

这解决了手头的问题 - 我们检查了一个字符串,并且我们只在没有匹配的项目时返回(尽管你可能想开始将字符串转换为数据中的整数而不是对字符串的这个 hackish 修复/内部问题)。

我还改变了你循环的方式——使用生成器表达式使语法更自然,对字典中的命名属性使用正常的构造语法。这比使用 _makemap() 更清晰、更易读。它还解决了问题 3。

关于python - 在 CSV 文件中搜索特定值的单个列并返回整行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10209641/

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