无法从 Python 中搜索 csv 文件获得结果

Cannot obtain result from searching csv file in Python

对于一项作业,我必须编写一个程序,该程序可以在学术论文的制表符分隔文本文件中搜索某些值,即在作者列中搜索作者,然后打印整行。这是到目前为止的代码...

import csv
import sys

#Assign File to "SearchFile"
SearchFile=raw_input(str("Enter the name of the file you want to search: "))

#open csv
reader = csv.reader(open(SearchFile, "rb"), delimiter="\t")

#Search Request
search_request = raw_input(str("Search on author (A=)or journal/conference (J=), [Q = quit]: "))

#Author Search
if search_request.startswith("A="):
    for row in reader:
        if search_request in row[0]:
            print row
        else:
            print("Sorry, could not be found")

我在Whosebug上看过一些类似的例子,但还是不能解决我的问题。我可以让它通读文件,但似乎无法检索任何搜索结果?我是 Python 的新手,所以如果有人能提供帮助那就太好了!

csv 文件的一些行:

AUTHOR(S)    YEAR    TITLE    JOURNAL/CONFERENCE
Accot;Zhai  2001    Scale effects in steering law tasks Proc. ACM CHI
Acredolo    1977    Developmental Changes in the Ability to Coordinate Perspectives of a Large-Scale Space  Developmental Psychology

至少这不起作用的原因之一是因为您忘记了 search_request 中有 "A="。很明显,这不是您的意思:您想要在 row[0] 中搜索字符 after "A="。所以你需要先把 "A=" 去掉 search_request...

if search_request.starts_with("A="):
    seach_request = search_request[2:]  # strip off the selector "A="
    for row in reader:
        if search_request in row[0]:
            print row
        else:
            print("Sorry, could not be found")
else:
  print("Ooops, your selection (%s) is not supported right now" % search_result[:2])

我认为行[0] 没有"A=" 前缀。您可能应该从 search_request 字符串中删除前缀。

...
#Author Search 
if search_request.startswith("A="): 
    for row in reader: 
        if search_request[2:] in row[0]:
            print row
        else: 
            print("Sorry, could not be found")