0
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
4

1 回答 1

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如果a 中的某些列 ( )line等于 ,则应该返回 true substring。例如,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
于 2013-04-06T14:57:37.080 回答