【问题标题】:Searching and sorting in text files在文本文件中搜索和排序
【发布时间】:2016-05-16 17:16:17
【问题描述】:

我对代码很陌生,但在读取文本文件时遇到了问题。 对于我的代码,我需要让用户输入特定的名称代码才能继续执行代码。但是,用户可以使用各种名称代码,我不知道如何制作,所以如果您输入任何一个代码,您就可以继续。

例如文本文件如下所示

约翰123,x,x,x

susan233,x,x,x

康纳,x,x,x

我需要做的是接受名称标签,不管它是什么标签,并且能够在之后打印它。所有名称标签都在一列中。

file = open("paintingjobs.txt","r")

details = file.readlines()


for line in details:
    estimatenum = input ("Please enter the estimate number.")
    if estimatenum = line.split

到目前为止,这是我的代码,但我不知道该怎么做才能查看名称标签是否有效以让用户继续。

【问题讨论】:

  • 目前还不清楚您要在这里做什么。预期的输出是什么?
  • 给定用户输入,你能给出一个你期望的输出的具体例子吗?无论如何,要检查用户输入是否存在于文本文件的一行中,您可以使用“ifestimatenum in line:”。

标签: python file python-3.x text


【解决方案1】:

这是另一个解决方案,没有pickle。我假设您的凭据每行存储一个。如果没有,你需要告诉我它们是如何分开的。

name = 'John'
code = '1234'

with open('file.txt', 'r') as file:
    possible_match = [line.replace(name, '') for line in file if name in line]

authenticated = False

for item in possible_match:
    if code in tmp: # Or, e.g. int(code) == int(tmp) 
        authenticated = True
        break

【讨论】:

    【解决方案2】:

    您可以使用名为pickle 的模块。这是一个 Python 3.0 内部库。在 Python 2.0 中,它被称为:cPickle;其他一切都是一样的。

    请注意,您执行此操作的方式并不安全!

    from pickle import dump
    
    credentials = {
        'John': 1234,
        'James': 4321,
        'Julie': 6789
    }
    
    
    dump(credentials, open("credentials.p", "wb"))
    

    这会保存一个名为credentials.p 的文件。您可以按如下方式加载:

    from pickle import load
    
    credentials = load(open("credentials.p", "rb"))
    
    print(credentials)
    

    这里有几个测试:

    test_name = 'John'
    test_code = 1234
    

    这相当于:

    print('Test: ', credentials[test_name] == test_code)
    

    显示:{'John': 1234, 'James': 4321, 'Julie': 6789}

    显示:Test: True

    test_code = 2343
    print('Test:', credentials[test_name] == test_code)
    

    显示:Test: False

    【讨论】:

    • 为什么要把pickle 带进来?
    • 恐怕我真的不能使用任何进口,我希望找到一个没有任何进口的解决方案。非常感谢您的帮助!
    • 简单的方法。做他们想做的最简单的方法。 Python 的内部库。以与保存时相同的结构打开数据,即在本例中为 dict
    猜你喜欢
    • 1970-01-01
    • 2019-11-28
    • 2018-11-16
    • 2019-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多