【问题标题】:Python - Counting number of visits a user has madePython - 计算用户的访问次数
【发布时间】:2016-08-31 18:08:29
【问题描述】:

我正在开发一个程序,我即将结束它,我刚刚在我的聊天机器人中实现了让机器人记住已经与他们交谈过的用户的能力。通过将用户给我的聊天机器人的名称保存到文本文件很容易完成,但是为了结束我的程序,我希望能够跟踪用户与我的聊天机器人交谈的次数,但我不确定如何去做吧。

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

#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()

显示“欢迎回来”消息的位置,在其末尾,我想显示用户登录与聊天机器人交谈的次数

【问题讨论】:

  • 到目前为止你尝试过什么?您可以使用collections.Counter
  • @Bahrom 这是我第一次写入文件,因为我刚刚开始学习 Python,所以除了将用户名保存到文件中,没有别的
  • 到目前为止发布您的代码(只是基本部分)。有一个样本输入/输出会有所帮助。这样的问题相当广泛。例如,你是如何写名字的?
  • 看看shelve module

标签: python file text store


【解决方案1】:

如果您通过网络进行操作,您可以使用 cookie 吗?否则我会说通过上面提到的 JSON 模块来完成

【讨论】:

    【解决方案2】:

    使用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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-09
      相关资源
      最近更新 更多