选项卡分隔列文件中的Python搜索功能

时间:2013-04-06 13:34:57

标签: python input raw-input function

while True:
    try:
        OpenFile=raw_input(str("Please enter a file name: ")) 
        infile=open(OpenFile,"r")
        contents=infile.readlines()
        infile.close()

        user_input = raw_input(str("Enter A=<animal> for animal search or B=<where lives?> for place of living search: \n")) 
        if user_input.startswith("A="):
            def find_animal(user_input,column):
                return next(("\t".join(line) for line in contents
                             if line[column-1]==user_input),None)
            find_animal(user_input[1:]) 
            print str((find_animal(user_input[1:], "WHO?"))) #"Who?" is the name of the first column.

        else:
            print "Unknown option!"


    except IOError:
        print "File with this name does not exist!"

1.输入动物名称。

2.Program在第一列中搜索具有此特定名称的行。

3.Program在第一列中打印具有此名称的行。

我的功能似乎无法在这里正常工作。你能帮我找一下这个错误吗?谢谢!

修改

      def ask_for_filename():
         filename=str(raw_input("Please enter file name: "))
         return filename

      def read_data(filename): 
         contents=open(filename,"r")
         data=contents.read()
         return data

      def  column_matches(line, substring, which_column):  
         for line in data:
             if column_matches(line, substring, 0):
                print line

1 个答案:

答案 0 :(得分:0)

大块代码难以阅读和调试,尝试将代码拆分为更小的函数,例如:

def ask_for_filename():
    #left as an exercise
    return filename

def read_data(filename):
    #left as an exercise
    return data

def column_matches(line, substring, which_column):
    #left as an exercise

def show_by_name(name, data):
    for line in data:
        if column_matches(line, name, 0):
            print line

def do_search(data):
    propmt = "Enter A=<animal> for animal search or B=<where lives?> for place of living search: \n"
    user_input = raw_input(prompt)
    if user_input.startswith('A='):
        show_by_name(user_input[2:], data)

# main program

filename = ask_for_filename()
data = read_data(filename)
while True:
    do_search(data)

单独测试和调试这些功能,直到您确定它们正常工作。然后编写并测试主程序。

如果column_matches()中的某些列(which_column)等于line,则

substring应返回true。例如,column_matches("foo\tbar\tbaz", "bar", 1)True。实现这个目标

  • 用分隔符分割一行 - 这为我们提供了一个值列表
  • 获取列表的第n个元素
  • 将其与次级
  • 进行比较
  • 如果相等则返回True,否则返回False

全部放在一起:

def column_matches(line, substring, which_column):
    delimiter = '\t'
    columns = line.split(delimiter)
    value = columns[which_column]
    if value == substring:
        return True
    else:
        return False

或者,以更简洁和“pythonic”的形式:

def column_matches(line, substring, which_column):
    return line.split('\t')[which_column] == substring