简体   繁体   English

将文本文件转换为列表,然后阅读列表以确定条目是否在列表中

[英]Converting a text file to list and then reading list to determine if an entry is within the list

I'm having a little trouble with converting a text file to a list. 将文本文件转换为列表时遇到了一些麻烦。 the text file is presented like this: 文本文件显示如下:

5658845
4520125
7895122
8777541
8451277
1302850
8080152

I have written code that takes user input and tries to determine if the user input is in the list. 我编写了接受用户输入并尝试确定用户输入是否在列表中的代码。 I am however having some trouble in searching the list as I can only get a result on the last result in the list, where am I going wrong? 但是,我在搜索列表时遇到了一些麻烦,因为我只能从列表中的最后一个结果中获取结果,我在哪里出错?

def accountReader():

    while True:
        chargeInput = (raw_input ("Enter a charge account to be validated: "))
        if chargeInput == '':
            break
            sys.exit


        else:
            chargeAccount = open('charge_accounts.txt', 'r')
            line = chargeAccount.readline()
            while line != '':
                if chargeInput == line:
                    print chargeInput, 'was found in list.'                    
                else:
                    print chargeInput, 'not found in list.'
                    break           


    chargeFile.close  

i would read the list like this 我会这样阅读清单

chargeAccount = open('charge_accounts.txt', 'r')
accts = [line.strip() for line in chareAccount]

if chareInput in accts:
  #do something
else:
  #do something else

at the very least .strip() off the readline(), your line likely looks like '5658845\\n' 至少在readline()的.strip()处,您的行可能看起来像是“ 5658845 \\ n”

UPDATE UPDATE

so after testing what you have with my modification it works....except it repeats indef do to the while acct != '' 因此,在测试了我的修改后,它可以正常工作....除了它对while acct重复indef!=''

here is what I changed 这是我改变的

chargeAccount = open('charge_accounts.txt', 'r')
  accts = [line.strip() for line in chargeAccount]
  while accts != '':
     if chargeInput in accts:
        #...

I would ditch the while loop altogether, it is either in the list or its not. 我完全放弃了while循环,它要么在列表中,要么不在列表中。 no need to cycle through each line. 无需在每一行中循环。

A line-by-line breakdown: 逐行细分:

def accountReader():

    while True:
        chargeInput = (raw_input ("Enter a charge account to be validated: "))
        if chargeInput == '':
            break
            sys.exit

Ok, so far so good. 好的,到目前为止很好。 You've created a loop that repeatedly asks the user for input and breaks when the user inputs nothing. 您已经创建了一个循环,该循环反复询问用户输入内容,并在用户未输入任何内容时中断。

        else:
            chargeAccount = open('charge_accounts.txt', 'r')
            line = chargeAccount.readline()

Here's where you start running into problems. 这是您开始遇到问题的地方。 readline reads a single line from chargeAccount and stores it in line . readlinechargeAccount读取一行并将其存储在line That means you can only test one line! 这意味着您只能测试一条线!

            while line != '':
                if chargeInput == line:
                    print chargeInput, 'was found in list.'

This further compounds your problem. 这进一步加剧了您的问题。 If chargeInput == line , then this prints a message and then the loop repeats. 如果chargeInput == line ,则打印一条消息,然后循环重复。 Since there's nothing to break out of the loop, this will result in an infinite loop that constantly tests one single line from the file. 由于没有任何问题可以打破循环,因此将导致无限循环,不断测试文件中的一行。 Also, because each line from the file ends with a newline ( \\n ), chargeInput == line will always yield false (thanks Steven Rumbalski for reminding me of this). 另外,由于文件中的每一行都以换行符( \\n )结尾, chargeInput == line始终产生false(感谢Steven Rumbalski提醒我这一点)。 Use .strip() (as suggested in matchw's answer), or, if you can tolerate partial matches, you could use Python's simple substring matching functionality: if chargeInput in line . 使用.strip() (根据matchw的答案中的建议),或者,如果您可以容忍部分匹配,则可以使用Python的简单子字符串匹配功能: if chargeInput in line

                else:
                    print chargeInput, 'not found in list.'
                    break           


    chargeFile.close  

And here, as sarnold pointed out, you've misnamed your file; 正如sarnold所指出的,您在这里给文件起了错误的名字。 furthermore, it's in a completely different block of code, which means that you repeatedly open chargeAccount files without closing any of them. 此外,它位于完全不同的代码块中,这意味着您反复打开chargeAccount文件而不关闭它们中的任何一个。

As you can see from matchw's post, there is a much simpler way to do what you're trying to do. 从matchw的帖子中可以看到,有一种简单得多的方法可以完成您想做的事情。 But I think you'd do well to figure out how to write this code correctly in the style you've chosen. 但是,我认为您会很好地弄清楚如何以所选的样式正确编写此代码。 I'll give you one hint: there should be a line = chargeAccount.readline() inside the innermost while loop. 我给你一个提示:应该有一个line = chargeAccount.readline()最里面的while循环 Do you see why? 你明白为什么吗? Also, you should probably exit the loop when you succeed in finding a match, not when you fail. 同样,您应该在成功找到匹配项时退出循环,而不是在失败时退出循环。 Then you should think about a way to test whether the search was a success after the innermost loop has completed. 然后,您应该考虑一种方法,以测试最内层循环完成后搜索是否成功。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM