![](/img/trans.png)
[英]Python: How can I search a text file for a string input by the user that contains an integer?
[英]How can I search a specific column in text file for a user input
我希望能夠向用戶詢問他們想要在特定列中搜索的字符串。 它是制表符分隔文本文件中的第二列,查找並打印該列中出現的每個實例。
我希望用戶能夠只輸入項目的片段,無論大寫還是小寫,並獲取完整的項目。 在這種情況下,第二列包含作者列表,我希望用戶能夠搜索作者並返回作者的姓名和他們寫的書的名稱,這是在同一行,但是在第一列。
def file_search():
userInput = input('Enter a string: ')
lowerInput = userInput.lower()
f=open('file.txt','r')
lowerInput=f.readlines()
result=[]
for x in lowerInput:
result.append(x.split(' ')[1])
f.close()
這是我嘗試過但我的'列表索引超出范圍'一條線看起來像
A Widow For One Year John Irving Random House 6/14/1998 Fiction
Accident Danielle Steel Delacorte 2/27/1994 Fiction
Acheron Sherrilyn Kenyon St. Martin's 8/24/2008 Fiction
Advise and Consent Allen Drury Doubleday 10/4/1959 Fiction
Against All Enemies Tom Clancy Putnam 7/3/2011 Fiction
Airframe Michael Crichton Knopf 12/29/1996 Fiction
Airport Arthur Hailey Doubleday 4/7/1968 Fiction
我已經修改了你的代碼,但它肯定會讓你去。 例如,如果您輸入“john”,您將找到有關其工作的所有信息。
def file_search():
userInput = input('Enter a string: ').lower()
result = []
with open("file.txt", 'r') as f:
for x in f:
if userInput in x.lower():
result.append(x.split(' '))
for s in result:
print(s[1] + " has written: "+ s[0])
file_search()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.