在CSV中搜索项目
我试图通过.csv文件(我在Excel中打开)进行搜索并在字段中查找特定数字。我正在搜索的号码来自GUI中的用户输入。如果在该字段中找到该号码,则将输出同一行中的其他字段中的所有项目。这是该文件的内容: screen shot of the file in excel 问题是,我似乎无法创建一段可以通过.csv读取并查找编号的代码。 这是我到目前为止(这只是不工作的代码部分):在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
如果你有一个解决方案,请给我的代码,将尽正是我需要它去做。如果你解释了它做了什么,我将不胜感激,但如果你不这样做并不重要。感谢您提前回复。
你能做到这样使用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
正是我需要的!我需要编辑它有点为它与程序的其余部分正常工作,否则我不能要求更多。非常感谢。此外,如果你可以告诉我每条线路是什么,那么我可以在将来使用它,我会很感激它,但不要像你必须那样下跌。 – Matthew64
这里是大熊猫的解决方案:
让我们开始创建示例数据:
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']]
感谢您的回答,我会向任何有类似问题但不是同一问题的人推荐此答案。 – Matthew64
欢迎来到SO。所以你想要一个答案,但不关心,如果没有解释?你没有兴趣学习后来自己使用它们的功能吗? –
_“给我的代码将完成我所需要的”_堆栈溢出不是一个真正的“免费代码写入服务”,更多的是一个学习的地方。可能想看看[游览]。 – ashleedawg
对不起,这两个人说我错误地使用了网站,但是当我连续编写了将近12个小时而没有运气的时候,我非常渴望得到答案。我将铭记未来。 – Matthew64