在单个列中搜索CSV文件中的特定值,然后返回整行
问题
该代码无法正确识别输入(项目)。即使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。
尽管可以对每个字段名称进行硬编码,但我认为,如果程序可以在打开文件时读取它们,那么在处理具有相同列名但具有不同列组织的相似文件时,它将大有帮助。
研究
- CSV标头和命名元组: 将CSV文件数据作为namedtuple行读取的pythonic方法是什么?
- 将CSV数据转换为元组:如何拆分CSV行,以便row [0]是名称,其余所有项都是元组?
- 还有其他研究链接,但我不能发表两个以上的链接。
-
您有三个问题:
- 您将在第一次失败后返回,因此它将永远不会超过第一行。
- 您正在从文件中读取字符串,并与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
这可以解决当前的问题-我们将检查字符串,并且仅在没有匹配项的情况下才返回(尽管您可能希望开始将字符串转换为数据中的整数,而不是针对字符串/
int问题进行此修正) 。我还改变了循环的方式-
使用生成器表达式使语法更自然,对dict中的命名属性使用常规构造语法。与使用_make
和相比,此方法更清晰易读map()
。它还可以解决问题3。