我有一个用制表符分隔的文本文件(每个列都负责某个组件):1 (who?) 2 (age) 3 (Does what?) 4 )(where lives?)
A Dog 4 Walks Lives in a box
B Parrot 2 Eats Lives in a cage
C Cat 3 Sleeps Lives in a house
用户必须在两个选项中选择一个来查找关于动物的所有信息。用户可以在第一列或第四列输入猜测:
^{pr2}$
或者4=Live in a box**
如果有匹配的,它会打印出整条线。在在第一种情况下,如果用户决定使用第一列(谁?)在中查找有关动物的信息将显示:Cat 3 Sleeps Lives in a house
在第二种情况下,如果用户决定使用第四列(where lives?)在中查找有关动物的信息将显示:Dog 4 Walks Lives in a box
我需要的是找到一个合适的函数来搜索动物。我尝试使用search()和match()但没有用。在**EDIT after codesparkle's advice**
我似乎无法将建议的功能集成到我的程序中。我对第[column-1]行位特别困惑。我试着“玩”这个函数,但是我没有想出任何有用的东西。这是我需要完成的真正的代码。在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= for animal search or B= 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?"))) # I messed up the first time and gave numeric names to the columns. In reality they should have been words that indicate the proper name of the column. In this case it is WHO- the first column which signifies the animal.
else:
print "Unknown option!"
except IOError:
print "File with this name does not exist!"