-1

タブ区切りのテキスト ファイルがあります (すべての列が特定のコンポーネントを担当します)。

  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!"
4

1 に答える 1

0

入力が次のようになっていると仮定します (投稿した例には、タブではなくスペースが含まれています)。

Dog 4   Walks   Lives in a box
Parrot  2   Eats    Lives in a cage
Cat 3   Sleeps  Lives in a house

次のアプローチを取ることができます。

  1. ファイルを開いて行を読み取り、タブで分割して改行文字を削除します。

  2. 要求された列に検索語が含まれる最初の行を返す関数を作成します。この例でNoneは、何も見つからない場合に返されます。


with open('input.txt') as input_file:
    lines = [line.rstrip().split('\t')
             for line in input_file.readlines()]

def find_animal(search_term, column):
    return next(('\t'.join(line) for line in lines
                 if line[column-1] == search_term), None)

print(find_animal('Cat', 1))
print(find_animal('Lives in a box', 4))
于 2013-03-28T16:33:00.330 に答える