我正在尝试编写一个函数,允许用户输入名称或电话号码,检查它是否存在于文件中,以及是否打印出找到该元素的整行。我到目前为止:
def searchPlayer():
with open("players.txt") as f:
data = f.readlines()
print "Enter 0 to go back"
nameSearch = str(raw_input("Enter player surname, forname, email, or phone number: "))
if any(nameSearch in s for s in data):
#Finding the element in the list works
#Can't think of a way to print the entire line with the player's information
else:
print nameSearch + " was not found in the database"
文件的格式如下:
Joe;Bloggs;j.bloggs@anemailaddress.com;0719451625
Sarah;Brown;s.brown@anemailaddress.com;0749154184
因此,如果nameSearch == Joe,则输出应为Joe;Bloggs;j.bloggs@anemailaddress.com;0719451625
任何帮助将不胜感激,谢谢
答案 0 :(得分:2)
为什么不使用循环?
for s in data:
if nameSearch in s:
print s
break
无论如何,{p> any
正在从docs:进行循环播放
def any(iterable):
for element in iterable:
if element:
return True
return False
答案 1 :(得分:1)
似乎太复杂,只是做
with open("players.txt") as f:
for line in f:
if nameSearch in line:
print line
答案 2 :(得分:1)
您不能像其他人提到的那样使用any
,但如果您想保留更紧凑的代码,则可以使用next
。而不是:
if any(nameSearch in s for s in data):
entry = next((s for s in data if nameSearch in s), None)
if entry is not None:
print entry,
else:
print nameSearch, "was not found in the database"
注意:您可能希望使用csv.reader
或类似内容进行解析,否则您最终会误认为数据格式化;如果用户输入;
,您将盲目地返回第一条记录,即使;
是格式化,也不是字段数据。同样,搜索Jon
会找到名为Jon
或Jonathan
的第一个人或可能存在的以Jon
开头的任何其他名称。
答案 3 :(得分:0)
正如@alexis在评论中提到的,如果您想知道哪一行匹配,则不应使用any()
。在这种情况下,您应该使用循环:
found = False
for s in data:
if nameSearch in s:
print s
found = True
#break # Optional. Put this in if you want to print only the first match.
if not found:
print "{} was not found in the database".format(nameSearch)
如果您只想打印第一个匹配项,请在break
之前取出哈希符号,然后将if not found:
更改为else:
。