【问题标题】:Searching for Item in CSV在 CSV 中搜索项目
【发布时间】:2017-10-28 21:06:04
【问题描述】:

我正在尝试搜索 .csv 文件(我在 Excel 中打开)并在字段中查找特定数字。我正在搜索的数字来自 GUI 中的用户输入。如果在该字段中找到该数字,则将输出同一行中其他字段中的所有项目。这是文件中的内容: screen shot of the file in excel 问题是我似乎无法创建一段可以读取 .csv 并找到数字的代码。 这是我到目前为止所拥有的(这只是代码中不起作用的部分):

def search(): # defining the function
term=str(e3.get()) # getting the user input and setting it to the varible 'term'
import csv # from all my researching, this is required to open the file
open('Book1.csv') # opens the file
# the code to look through the file would be here. It must search for the number in the correct field and output an error if it can't find it
print() #this will print the data in the same row as the number from the different fields for the user

如果您有解决方案,请给我代码,它可以完全满足我的需要。如果您解释它的作用,我将不胜感激,但如果您不解释也没关系。感谢您提前回复。

【问题讨论】:

  • 欢迎来到 SO。所以你想要一个答案,但不在乎它是否没有解释?您没有兴趣学习这些功能以供以后自己使用吗?
  • “给我我需要的代码” ...Stack Overflow 并不是真正的“免费代码编写服务”,更多的是学习的地方。可能想查看tour
  • 对说我错误地使用该网站的两个人感到抱歉,但当我连续编码近 12 个小时却没有运气时,我迫切希望得到答案。我会牢记您的建议,以备不时之需。

标签: python excel csv


【解决方案1】:

您可以使用 python 的 csv 模块这样做:

import csv

def search():
    term = #something
    reader = csv.reader(open('Book1.csv', 'r'))
    for row in reader:
        if row[0] == term:
            return row[1:]
    return None # return None if no match

【讨论】:

  • 正是我需要的!我需要对其进行一些编辑,以使其与程序的其余部分正常工作,否则我无法要求更多。非常感谢。另外,如果您能告诉我每条线的作用,以便我将来可以使用它,我将不胜感激,但不要像必须这样做一样跌倒。
【解决方案2】:

这里是熊猫解决方案:

让我们从创建示例数据开始:

import io
s = u"""bar_code,item,price
1,Spam,0.1
2,Beans,0.2
3,Egg,0.2
4,Milk,0.3"""

file = io.StringIO(s)

现在是实际代码:

import pandas as pd
df = pd.read_csv(file) 
#df = pd.read_csv('Book1.csv')

lookup = 0.2 # lookup value
matches = df[df['price'] == lookup] # filter rows

# if you find items
if len(matches)>0:
    items = matches.drop('price', axis=1).values.tolist() #drop price column
    print(items)
else:
    print("No match!")

返回:

[[2, 'Beans'], [3, 'Egg']]

【讨论】:

  • 感谢您的回答,我会向任何遇到类似问题但不一样的人推荐此答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-06
相关资源
最近更新 更多