【问题标题】:Python Search function in a tab delimited column file制表符分隔的列文件中的 Python 搜索功能
【发布时间】:2013-04-06 13:34:56
【问题描述】:
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.程序在第一列中搜索具有此特定名称的行。

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

【问题讨论】:

  • 不需要在字符串上调用str()

标签: python input raw-input function


【解决方案1】:

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

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)

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

如果line 中的某个列(which_column)等于substring,则column_matches() 应该返回true。例如,column_matches("foo\tbar\tbaz", "bar", 1)True。实现这一目标

  • 用分隔符分割一行 - 这给了我们一个值列表
  • 获取列表的第 n 个元素
  • 将其与 substing 进行比较
  • 如果相等则返回 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

【讨论】:

  • 感谢您的帮助。我试图完成练习,但我无法真正理解在第三个功能中我必须做什么[见编辑]。你能不能解释一下我必须在那里做什么?
  • @AlButter:我添加了更多细节。
  • 感谢您的帮助,现在我完全了解如何正确使用函数了。顺便说一句,您能否建议任何好的 Python 课程并提供详尽的分步解释?
  • @AlButter: diveintopython.net - 我没读过,但有人说很好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-31
  • 1970-01-01
  • 2015-06-19
  • 1970-01-01
  • 2013-01-21
  • 2023-04-07
相关资源
最近更新 更多