python - 如何在文本文件中的特定列中搜索用户输入

标签 python python-3.x

我希望能够向用户询问他们想要在特定列中搜索的字符串。它是制表符分隔文本文件中的第二列,查找并打印该列中出现的每个实例。

我希望用户能够只输入项目的一小段,不管大写还是小写,然后得到完整的项目。在这种情况下,第二列包含作者列表,我希望用户能够搜索作者并返回作者的姓名和他们所写的书的名称,它们在同一行中,但是在第一列。

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/

相关文章:

python pandas 将多年的 yyyy-mm-dd 分配为累计周数

python - 发送一个 python 修饰方法作为函数参数

python - 将 dict 的 pandas dataframe 列扩展为 dataframe 列

python - 从其他文件导入类时 PyCharm 未解析的引用

python-3.x - 类型错误 : Improper input: N=2 must not exceed M=1

python - 我怎样才能按字母顺序对这本字典进行排序?

python - 如何绘制等长的动态线段

python - 使用 Python 检测重复文件

python - 在Python 3中将出生日期pandas数据框分成3个不同的列

python - 括号内的非贪婪正则表达式并包含文本