简体   繁体   English

用户输入搜索后将txt文件转换为列表并返回行

[英]Converting txt file to list and returning line after user input search

I'm trying to have the user input a telephone number, then the program will open a text file, convert it to a list, search the list and if the phone number is found it will return the rest of the line (which contains the address for that phone number. 我正在尝试让用户输入电话号码,然后程序将打开一个文本文件,将其转换为列表,搜索列表,如果找到了电话号码,它将返回该行的其余部分(其中包含该电话号码的地址。

I can only get it to return either "phone number not found" or the line but it does it for every single line so I end up with an output like this: 我只能让它返回“找不到电话号码”或该行,但是它对每一行都执行此操作,因此最终得到这样的输出:

phone number not found
phone number not found
0121 254132 18 Springfield Road
phone number not found
phone number not found

for line in phonenumbers:

    if number in line:
        print (line)
    else:
        print ("phone number not found")

I know it's because I've put for line in phonenumbers but don't know how to not do it for every line. 我知道这是因为我已经在电话号码中加入了行号,但不知道如何不对每一条线都这样做。

try the following: 尝试以下方法:

for line in phonenumbers:    
    if number in line:
        print (line)
        break
else:
    print ("phone number not found")

the else is part of the for loop and will only execute if you didn't break out of the for loop. else的部分for循环,如果你没有将只执行break了的for循环。

Why do you not just drop the else statement. 您为什么不只删除else语句。 It should look something like: 它看起来应该像这样:

for line in phoneNumbers:
  if phone in line:
     print line

If you want a result in case that it was not found you could use a flag. 如果希望得到结果,以防找不到,可以使用标志。 moreover you can just use: 此外,您可以使用:

print [line for line in phonenumbers if number in line]

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

相关问题 输入验证并将元组列表转换为 txt 文件 - Input validation and converting list of tuples to txt file 将.txt文件转换为列表并能够逐行索引和打印列表 - Converting .txt file to list AND be able to index and print list line by line 如何使用 2 组用户输入搜索 txt 文件,然后打印相关行? - How to search a txt file using 2 sets of user input, then print the associated line? 用用户输入搜索并替换.txt文件中的字符串 - Search and replace string inside .txt file with user input 用户输入后返回 html 文件和 django - returning html file with django after user input 将txt文件转换为字典列表 - Converting txt file into a list of dictionaries 如何从用户输入中搜索单词列表的文本文件,并打印包含这些单词的行? - how can i search a text file of list of words from user input and print the line which contains these words? Python在txt文件中搜索输入 - Python search for input in txt file 计算txt文件中的单词出现次数,返回字典并将字典在类的帮助下转换为列表 - Counting word occurances in txt file, returning dictionary and converting dict to list with the help of classes 如何在txt文件中搜索。 显示包含指定表达式的行和之后的行? - How to search in a txt file. Show the line that contains the specified expression and the line after that?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM