2016-05-05 1 views
0

私はプログラムに取り組んでいます。私はそれを終わりにしています。私はチャットボットに、すでに彼らに話されている。ユーザーが私のチャットボットをテキストファイルに保存することで簡単に行えましたが、プログラムを終了するには、ユーザーがチャットボットに何回話したのかを知ることが大好きですが、それをやる。Python - ユーザーが訪問した回数をカウントする

テキストファイルに保存する必要があることは知っていますが、各ユーザーに訪問回数を与えるにはどうすればよいですか?その「おかえりなさい」のメッセージが表示され、それの終わりに、私はチャットボットと話すために、ユーザがログインした回数を表示したい

enter image description here

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

+3

これまでに何を試しましたか? ['collections.Counter'](https://docs.python.org/2/library/collections.html#collections.Counter)を使用できます。 – Bahrom

+0

@Bahromファイルにユーザ名を保存する以外に、Pythonを拾い始めたばかりなので、初めてファイルに書き込むのは初めてです。 –

+2

これまでのコードを投稿するだけです。サンプルの入力/出力が役立ちます。問題はこのように幅広いです。あなたはどのように名前を書いていますか? – Bahrom

答えて

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) 
0

ウェブ経由で送信する場合は、Cookieを使用できますか?それ以外の場合は、上記のようにJSONモジュールを使用してください。

関連する問題