2016-11-19 71 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

如何使用Pandas 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]),:] 

此解決方案當然假設您可以將文件讀入內存。