我是Python编程的新手,几个小时都无法解决以下问题。我有包含四行的示例文件。我希望在文件行中找到来自用户的两个输入,但是我的循环似乎没有遍历所有行。这是文件的内容,元素用空格分隔:
Google 1 2
Apple 13 17
Microsoft 22 8
Verizon 6 15
这是我的代码:
import sys
with open('manylines.txt','r') as myfile:
results = [line.split() for line in myfile]
for i in results:
print(i)
term1=input("Enter the first term:")
while term1 not in i :
print("Term not found,please try again:")
term1 = input("Enter the first term:")
term2 = input("Enter the second term:")
while term2 not in (i) :
print("Term not found,please try again:")
term2 = input("Enter the second term:")
print(i)
print(i)
sys.exit()
我希望输入例如Google和Microsoft,并获得以下输出:
['Google','1','2']
['Microsoft','22','8']
作为两个清单。但是,我的代码只查找第一行而不是其他行。你能告诉我为什么它不会迭代其他行。如何解决这个问题?提前谢谢!
答案 0 :(得分:0)
以下内容不会改变您尝试的代码......它使用lower()
和title()
来允许用户输入的各种大小写:
import sys
with open('data.txt','r') as f:
results = [line.split() for line in f]
while True:
found = False
term = input("Enter a company to search or type exit: ")
if term.lower() == "exit":
break
for record in results:
if record[0] == term.title():
print(record)
found = True
break
if not found:
print("Term not found, please try again...")
print("Goodbye!")
sys.exit(0)
使用示例:
Enter a company to search or type exit: Google
['Google', '1', '2']
Enter a company to search or type exit: microsoft
['Microsoft', '22', '8']
Enter a company to search or type exit: Amazon
Term not found, please try again...
Enter a company to search or type exit: Exit
Goodbye!
以下是您只能向用户提示“两个术语”的方法:
out1, out2 = [], []
term_count = 1
while term_count < 3:
found = False
term = input("Enter term %d or type exit: " % term_count)
if term.lower() == "exit":
break
for record in results:
if term_count == 1 and record[0] == term.title():
print(record)
out1 = list(record)
found = True
term_count += 1
break
if term_count == 2 and record[0] == term.title():
print(record)
out2 = list(record)
found = True
term_count += 1
break
if not found:
print("Term not found, please try again...")
使用示例:
Enter term 1 or type exit: Amazon
Term not found, please try again...
Enter term 1 or type exit: Google
['Google', '1', '2']
Enter term 2 or type exit: Microsoft
['Microsoft', '22', '8']
Goodbye!
答案 1 :(得分:0)
尝试以下代码。此代码标识找到的术语,并询问未找到的术语。
你没有正确地进行循环。当您的循环第一次执行时,它有Google,而term1包含Google,term2包含Microsoft。所以它打印谷歌,之后你使用 sys.exit()来加强执行。所以当然它打印的第一行不是其他的。
import sys
with open('tempa.txt','r') as myfile:
results = [line.split() for line in myfile]
NeedToExecute = 0
term1 = False
term2 = False
list1 = None
list2 = None
while NeedToExecute != 2:
if(term1 != True):
term1 = input("Enter the first term:")
if(term2 != True):
term2 = input("Enter the second term:")
for i in results:
if term1 in i :
NeedToExecute = NeedToExecute + 1
term1 = True
list1 = i
print(i)
if term2 in i :
NeedToExecute = NeedToExecute + 1
term2 = True
list2 = i
print(i)
print list1
print list2