タブ区切りのテキスト ファイルがあります (すべての列が特定のコンポーネントを担当します)。
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
ユーザーは、動物に関するすべての情報を見つけるための 2 つのオプションから選択する必要があります。ユーザーは推測を最初の列または 4 番目の列に入力できます。
1=Cat*
また
4=Live in a box**
一致する場合は、行全体を出力します。
最初のケースで、ユーザーが最初の列 (who?) を使用して動物に関する情報を検索すると、次のように表示されます。
Cat 3 Sleeps Lives in a house
2 番目のケースで、ユーザーが 4 番目の列 (どこに住んでいますか?) を使用して動物に関する情報を検索すると、次のように表示されます。
Dog 4 Walks Lives in a box
必要なのは、動物を検索する適切な関数を見つけることです。search() と match() を使用してみましたが、役に立ちませんでした。
**EDIT after codesparkle's advice**
アドバイスされた機能をプログラムに統合できないようです。私は特に line[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=<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?"))) # 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!"