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

发布于 2024-11-09 09:51:02 字数 833 浏览 0 评论 0原文

我在将文本文件转换为列表时遇到了一些麻烦。 文本文件的呈现方式如下:

5658845
4520125
7895122
8777541
8451277
1302850
8080152

我编写了接受用户输入并尝试确定用户输入是否在列表中的代码。然而,我在搜索列表时遇到了一些麻烦,因为我只能得到列表中最后一个结果的结果,我哪里出错了?

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'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  

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

萌无敌 2024-11-16 09:51:02

逐行细分:

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()

这就是你开始遇到问题的地方。 readlinechargeAccount 读取一行并将其存储在 line 中。这意味着您只能测试一根线!

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

这进一步加剧了你的问题。如果 chargeInput == line,则打印一条消息,然后重复循环。由于没有任何东西可以打破循环,这将导致无限循环,不断测试文件中的一行。另外,因为文件中的每一行都以换行符 (\n) 结尾,所以 chargeInput == line 将始终产生 false(感谢 Steven Rumbalski 提醒我这一点)。使用 .strip() (如 matchw 的答案中所建议的),或者,如果您可以容忍部分匹配,则可以使用 Python 的简单子字符串匹配功能:if chargeInput in line

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


    chargeFile.close  

在这里,正如 sarnold 指出的那样,您的文件命名错误;此外,它位于完全不同的代码块中,这意味着您可以重复打开 chargeAccount 文件而不关闭任何文件。

正如您从 matchw 的帖子中看到的,有一种更简单的方法可以完成您想要做的事情。但我认为您最好弄清楚如何以您选择的样式正确编写此代码。我给你一个提示:最里面的 while 循环内应该有一个 line = chargeAccount.readline() 内部。你明白为什么吗?另外,当您成功找到匹配项时,而不是失败时,您应该退出循环。那么你应该考虑一种方法来测试最内层循环完成后搜索是否成功。

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. 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. 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). 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.

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


    chargeFile.close  

And here, as sarnold pointed out, you've misnamed your file; furthermore, it's in a completely different block of code, which means that you repeatedly open chargeAccount files without closing any of them.

As you can see from matchw's post, there is a much simpler way to do what you're trying to do. 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. 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.

南街女流氓 2024-11-16 09:51:02

会从 readline() 中读取这样的列表

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

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

我至少

,您的行可能看起来像 '5658845\n' UPDATE

所以在测试了我的修改后它可以工作....除了它对 while acct != '' 重复 indef do 之外,

这是我更改的内容

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

,我将完全放弃 while 循环,它要么在列表中,要么不在列表中。无需循环遍历每一行。

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'

UPDATE

so after testing what you have with my modification it works....except it repeats indef do to the while acct != ''

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. no need to cycle through each line.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文