从python中的文件中查找并列出来自不同列表的项目

时间:2013-09-12 08:27:52

标签: python string list find

如果我向程序提供列表中的特定项目,我想知道如何从列表中检索多个项目。这就是我的列表的样子:

["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以便于阅读。

2 个答案:

答案 0 :(得分:1)

您需要在列表中收集您的匹配项,然后将匹配的列表发送到您的聊天机器人:

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)调用将找到的名称与逗号连接起来,以便为名称提供更好,更易读的格式。

答案 1 :(得分:0)

“这是用于聊天机器人。第一项是用户名,第二项是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.

这将打印'saelyth'和'saelyth2',因为它们具有相同的IP地址。