在Python中查找.csv中的文本

时间:2018-02-08 01:50:29

标签: python csv search

在.csv文档中我有一行:

AAPL,"Apple Inc.","163.03","$827.22B","1980","Technology","Computer Manufacturing","https://www.nasdaq.com/symbol/aapl",

开始我的程序后,它会提示用户输入.csv文件路径以及要搜索的股票代码。在这种情况下,我正在寻找AAPL。

import csv
from tkinter import
import tkinter.simpledialog

root = Tk()
w = Label(root, text="Stock locator")
w.pack()

nasdaqDatabase = tkinter.simpledialog.askstring("NASDAQ Database", "Please input your NASDAQ database csv directory") 
webUrlTest = tkinter.simpledialog.askstring("Stock Ticker Input", "Input a stock ticker") 

with open(nasdaqDatabase, "r") as f:
    csvreader = csv.reader(f, delimiter=",")
    for row in csvreader:
        if webUrlTest in row[0]:
            print(webUrlTest + ' has been located in the NASDAQ')
        else:
            print('not found')
            quit()

运行代码搜索AAPL时的输出如下:

not found

Process finished with exit code 0

为什么不回复AAPL被发现?我在这个例子中哪里出错了?谢谢你的帮助!

2 个答案:

答案 0 :(得分:2)

for row in csvreader:
    if webUrlTest in row[0]:
        print(webUrlTest + ' has been located in the NASDAQ')
    else:
        print('not found')
        quit()

这将检查第一行,quit()是否不是您要查找的内容。当然你想要更像这样的东西:

found = False
for row in csvreader:
    if webUrlTest in row[0]:
        print(webUrlTest + ' has been located in the NASDAQ')
        found = True
if not found:
    print('not found')
    quit()

你也可以把它包装在一个函数中,以避免稍微笨拙的found标志;)

答案 1 :(得分:0)

如果任何行不是AAPL,则代码退出。您打算用else语句表达的是

for row in csvreader:
    if webUrlTest in row[0]:
        print(webUrlTest + ' has been located in the NASDAQ')
        break
else:
    print('not found')

有些人强烈反对for ... else陈述。他们会建议这种方法

found = False
for row in csvreader:
    if webUrlTest in row[0]:
        print(webUrlTest + ' has been located in the NASDAQ')
        found = True
        break
if not found:
    print('not found')

为了自己捕捉这种错误,我强烈建议使用python 调试器,这样你就可以单步执行并观察执行。有一个built in debugger,大多数IDE(例如PyCharm)都有调试器,接口很好。您可以搜索有关如何使用调试器的教程。