2016-11-19 6 views
0

NYTimesのベストセラー書籍を含むテキストファイルを見て、ユーザーがリストから書籍を検索して印刷できるようにするプログラムを作成しようとしています。パラメータ付きのテキストファイルからのPythonプリント

は現在、彼らが入力するブックの名前を含む行を印刷し、このコードを持っている:

def lookup(): 
    file= input("Please enter the text file path: ") 
    search = input("Enter the books you wish to search for: ") 
    search = [word.strip() for word in search.lower().split(",")] 
    with open(file, 'r') as f: 
     for line in f: 
      line = "\n" + line 
      for word in search: 
       if word.lower() in line.lower(): 
        print(line) 

lookup() 

私は年の範囲のためのユーザーの検索をさせるだろうか? txtファイルには、書籍名、著者、出版年などがすべて1つのタブスペースで区切られています。

+0

範囲を検索するのはややこしいですが、FWIWでは、[csv](https://docs.python.org/3/library/csv.html)モジュールを使用してデータをより簡単に読み取ることができます。私はあなたのファイルを辞書のリストに読み込むことをお勧めします。 –

答えて

1

パンダのread_csv関数の使用はどうですか?

import pandas as pd 

#reads in the tab delimited file 
df = pd.read_csv(file, delimiter ='\t') 

#gives all rows where the book year is 2000 or 2001 
#You can pass the list of years generated by the user to the isin() function 
df.loc[df.loc[:,'Year'].isin([2000, 2001]),:] 

この解決方法は、ファイルをメモリに読み込むことができることを前提としています。

関連する問題