我希望能够向用户询问他们想要在特定列中搜索的字符串。它是制表符分隔文本文件中的第二列,查找并打印该列中出现的每个实例。
我希望用户能够只输入项目的一小段,不管大写还是小写,然后得到完整的项目。在这种情况下,第二列包含作者列表,我希望用户能够搜索作者并返回作者的姓名和他们所写的书的名称,它们在同一行中,但是在第一列。
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()
关于python - 如何在文本文件中的特定列中搜索用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50920225/