【问题标题】:Would like to search for specific word/number inside a text file想在文本文件中搜索特定的单词/数字
【发布时间】:2019-11-25 09:02:54
【问题描述】:

大家好,我是 python 的新手,想知道如何在 Python 中专门搜索单词/数字,其结果是该单词来自的行。

staff.txt 包含类似的行信息

ID 名称 StartDate 角色

001 约翰 1-1-2001 Kitchenhand

002 迈克 2-1-2001 收银员

到目前为止,我的代码是这样的。我可以阅读 txt 文件,选择如何通过 ID 或电子邮件搜索员工。我只是迷失了如何编码它在 txt 文件中搜索 ID 的位。任何帮助或指导将不胜感激。

import random
choices = ["1","2"]
choice2a = random.choice(choices)

#   reads txt file
df = pd.read_csv('staff.txt', 'w', delimiter='\t')

#   deletes Unnamed columns
df = df.loc[:, ~df.columns.str.contains('^Unnamed')]

name= input("How would you like to search for staff?")
print ("1)ID")
print ("2)Email")
choice1 = input("Type Answer")#choice
if choice1 == "1" or choice1 == "1":
  input("Type staff ID")
  ID = ```

【问题讨论】:

    标签: python python-3.x pandas


    【解决方案1】:

    使用变量df 将文件读入内存,然后执行类似的操作

    # create a function
    def myFunc(df):
        # your input
        name = input(f"How would you like to search for staff? \n1) ID\n2) Email\n[1/2]: ")
        if name == '1': # if 1 ask for id input
            ids = input('Type ID number: ') # another input
            return df[df['ID'] == int(ids)] # boolean indexing to return df based on id
        elif name == '2': # if 2 ask for email address
            email =input('Type email address: ') # another input
            return df[df['email'] == email] # boolean indexing to return df based on email address
        else:
            raise ValueError(f'{name} is not 1 or 2') # raise value error if you enter a value other than 1 or 2
    
    myFunc(df) # run the function
    

    运行时的样子

    How would you like to search for staff? 
    1) ID
    2) Email
    [1/2]: 1
    Type ID number: 2
    
       ID   Name    StartDate      Role
    1   2   Mike    2-1-2001    Cashier
    

    【讨论】:

    • 我忘了提到我也在使用“import pandas as pd”。这是否会影响任何事情,或者我仍然可以将此作为我需要做的事情的指导方针吗?
    • @jvtji 您仍然可以将其用作指南该函数使用python内置函数
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-28
    • 1970-01-01
    • 2015-01-31
    • 1970-01-01
    • 2011-02-09
    • 1970-01-01
    • 2022-12-06
    相关资源
    最近更新 更多