[英]Find and list items from different lists from a file in python
如果我给程序列表中的特定项目,我想知道如何从列表中检索多个项目。 这是我的列表的样子:
["randomname", "188.xx.xx.xx", "uselessinfo", "2013-09-04 12:03:18"]
["saelyth", "189.xx.xx.xx", "uselessinfoalso", "2013-09-04 12:03:23"]
["randomname2", "121.xxx.xxx.x", "uselessinfoforstackoverflow", "2013-09-04 12:03:25"]
这是用于聊天机器人。 第一项是用户名,第二项是IP,我需要的是找到与同一IP相关的所有名称,然后打印它们或将其发送到聊天室,这是我所能做到的。
if message.body.startswith("!Track"):
vartogetname = vartogetip = None
filename = "listas\datosdeusuario.txt"
for line in open(filename, 'r'):
retrieved = json.loads(line)
if retrieved[0] == targettotrack:
vartogetname = retrieved[0]
vartogetip = retrieved[1]
break
#So far it has opened the file, check my target and get the right IP to track, no issues until here.
if not vartogetip == None: #So if has found an IP with the target...
print("Tracking "+targettotrack+": Found "+str(vartogetip)+"...")
for line in open(filename, 'r'):
retrieved2 = json.loads(line)
if retrieved2[1] == vartogetip: #If IP is found
if not retrieved2[0] == targettotrack: #But the name is different...
print("I found "+retrieved2[0]+" with the same ip") #Did worked, but did several different prints.
#HERE i'm lost, read text and comments after this code.
sendtochat("I found "+retrieved2[0]+" with the same ip") #Only sent 1 name, not all of them :(
else:
sendtochat("IP Not found")
在我说#HERE的地方,我需要一个代码来添加列表中找到的项目并将它们添加到另一个列表中(我想是吗?),然后可以在sendtochat命令中调用它,但是我必须真的很累,因为我不记得该怎么做。
我正在使用Python 3.3.2 IDLE,文件中的列表使用json保存,并且在末尾添加了\\n
以便于阅读。
您需要将匹配项收集在一个列表中,然后将该匹配项列表发送到您的聊天机器人:
if vartogetip is not None:
matches = []
for line in open(filename, 'r'):
ip, name = json.loads(line)[:2]
if ip == vartogetip and name != targettotrack:
matches.append(name)
if matches: # matches have been found, the list is not empty
sendtochat("I found {} with the same ip".format(', '.join(matches)))
', '.join(matches)
join ', '.join(matches)
调用将找到的名称与逗号连接在一起,以使名称更美观,更易读。
“这是用于聊天机器人的。第一项是用户名,第二项是IP,我需要的是查找与同一IP相关的所有名称,然后将其打印或发送给聊天,这是据我所知。”
似乎您想要的是将IP地址字符串映射到与该IP地址关联的用户名列表的字典。 也许尝试这样的事情:
user_infos = [
["randomname", "188.xx.xx.xx", 'data'],
["saelyth", "189.xx.xx.xx", 'data'],
["randomname2", "121.xxx.xxx.x", 'data'],
["saelyth2", "189.xx.xx.xx", 'data']
]
# Mapping of IP address to a list of usernames :)
ip_dict = {}
# Scan through all the users, assign their usernames to the IP address
for u in user_infos:
ip_addr = u[1]
if ip_addr in ip_dict:
ip_dict[ip_addr].append(u[0])
else:
ip_dict[ip_addr] = [u[0]]
# We want to query an IP address "189.xx.xx.xx"
# Let's find all usernames with this IP address
for username in ip_dict["189.xx.xx.xx"]:
print(username) # Have your chatbot say these names.
由于它们具有相同的IP地址,因此将同时打印“ saelyth”和“ saelyth2”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.