【问题标题】:Cannot obtain result from searching csv file in Python无法从 Python 中搜索 csv 文件获得结果
【发布时间】:2015-07-12 20:04:12
【问题描述】:

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

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")

我在 stackoverflow 上看到了一些类似的例子,但仍然无法解决我的问题。我可以让它读取文件,但似乎无法检索任何搜索结果?我是 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

【问题讨论】:

  • 你能把你正在搜索的 .txt 文件中的一行发给我们吗? :)
  • 在检查 startswith() "A=" 之前,您是否尝试过打印 search_request?你可能会发现它不是你想的那样。保护自己免受这种情况的另一件事是为 if startswith("A=") 设置一个 else 子句

标签: python database csv search multiple-columns


【解决方案1】:

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

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])

【讨论】:

  • 成功了,谢谢!对于您的其他评论,您对 else 子句是什么意思?不知道把它放在哪里,所以它不会为每一个不匹配的行声明“抱歉,找不到”,并且只有在没有匹配的情况下?
  • 我根据我的想法更新了答案。基本上,这个想法是始终检查“极端情况”,不要只是假设任何事情。您的代码将更健壮且更易于调试,因为它会更快地告诉您何时出现问题。
【解决方案2】:

我认为 row[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")

【讨论】:

    猜你喜欢
    • 2011-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-02
    • 2020-05-18
    相关资源
    最近更新 更多