[英]How can I search a specific column in text file for a user input
I want to be able to ask the user for a string that they would like to search for in a specific column. 我希望能够向用户询问他们想要在特定列中搜索的字符串。 Its the second column in a tab delimited text file, and find and print every instance where it occurs in that column.
它是制表符分隔文本文件中的第二列,查找并打印该列中出现的每个实例。
I want the user to be able to just enter even a snippet of the item, doesn't matter uppercase or lowercase, and get the full items back. 我希望用户能够只输入项目的片段,无论大写还是小写,并获取完整的项目。 In this case the second column contains a list of authors and I want the user to be able to search for an author and return the name of the author and the name of the book they've written, which is in the same line, but is in the first column.
在这种情况下,第二列包含作者列表,我希望用户能够搜索作者并返回作者的姓名和他们写的书的名称,这是在同一行,但是在第一列。
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()
This is what I've tried but my 'list index is out of range' A line looks like 这是我尝试过但我的'列表索引超出范围'一条线看起来像
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
I have modified your code a little bit but it should definitely get you going. 我已经修改了你的代码,但它肯定会让你去。 If for example you enter "john" you'll find everything about his work.
例如,如果您输入“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.