Python - 计算用户访问次数

时间:2016-05-05 20:04:57

标签: python file text store

我正在制作一个程序,我即将结束它,我刚刚在我的聊天机器人中实现了机器人能够记住已经与他们交谈过的用户的能力。通过保存用户将聊天机器人的名称保存到文本文件中轻松完成,但是为了结束我的程序,我希望能够跟踪用户与聊天机器人通话的次数,但我不知道如何做到这一点。

我知道它需要存储在文本文件中,但是如何为每个用户分配他们的访问次数?

#Defining the YouTube Channel function
def Maximus():
    #Holding the end user's name to make the chatbot more friendly
    userName = raw_input ("\nPlease enter your name: ")
    if userName in open('usernames.txt').read(): #Checks to see if user is pre-existing
        print ("Welcome back, %s. Good to see you again!" % (userName)) #If user is pr-existing, send this message
    else:
        print ("Nice to meet you %s, I'm Maximus, the friendly bot that helps to answer any questions you may have about YouTube's website!\nType quit to go back to the main menu." % (userName))
        fw = open('usernames.txt', 'a')
        fw.write("%s\n" % (userName)) #Creates the new user, which Maximus remembers
        fw.close()

enter image description here

显示“欢迎回来”消息的位置,在结尾处,我想显示用户使用聊天机器人登录的次数

2 个答案:

答案 0 :(得分:1)

使用json模块存储一个字典,其中包含名称作为键和访问次数作为值。

import json


def Maximus():
    # Holding the end user's name to make the chatbot more friendly
    userName = raw_input("\nPlease enter your name: ")

    with open('usernames.txt', 'r') as f:
        userCounts = json.load(f)

    if userName in userCounts:
        userCounts[userName] += 1
        print ("Welcome back, {}. Good to see you again! "
               "This is the {} time you have spoken to me.".format(
                   userName, userCounts[userName]))
   else:
       userCounts[userName] = 1
       print ("Nice to meet you {}, I'm Maximus, the friendly bot "
              "that helps to answer any questions you may have "
              "about YouTube's website!\nType quit to go back "
              "to the main menu.".format(userName))

    with open('usernames.txt', 'w') as f:
        json.dump(userCounts, f)

答案 1 :(得分:0)

如果您通过网络进行操作,可以使用Cookie吗?否则我会说通过上面提到的JSON模块来做​​这件事