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.輸入動物名稱。製表符分隔的列文件中的Python搜索功能
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()'。 – poke 2013-04-07 19:46:42