2016-06-09 6 views
0

Ich mache einen reddit Bot und ich habe es die Kommentar-IDs in einem Array gespeichert, so dass es nicht zweimal auf den gleichen Kommentar antwortet, aber wenn ich das Programm schließe Array ist gelöscht.Python lädt Variablen in ein Array aus der Datei

Ich bin auf der Suche nach einer Möglichkeit, das Array zu halten, wie es in einer externen Datei speichern und lesen, danke!

Hier ist mein Code:

import praw 
import time 
import random 
import pickle 

#logging into the Reddit API 
r = praw.Reddit(user_agent="Random Number machine by /u/---") 
print("Logging in...") 
r.login(---,---, disable_warning=True) 
print("Logged in.") 


wordsToMatch = ["+randomnumber","+random number","+ randomnumber","+ random number"] #Words which the bot looks for. 
cache = [] #If a comment ID is stored here, the bot will not reply back to the same post. 

def run_bot(): 
    print("Start of new loop.") 
    subreddit = r.get_subreddit(---) #Decides which sub-reddit to search for comments. 
    comments = subreddit.get_comments(limit=100) #Grabbing comments... 
    print(cache) 

    for comment in comments: 
     comment_text = comment.body.lower() #Stores the comment in a variable and lowers it. 
     isMatch = any(string in comment_text for string in wordsToMatch) #If the bot matches a comment with the wordsToMatch array. 

     if comment.id not in cache and isMatch: #If a comment is found and the ID isn't in the cache. 
      print("Comment found: {}".format(comment.id)) #Prints the following line to console, develepors see this only. 
      #comment.reply("Hey, I'm working!") 
      #cache.append(comment.id) 
while True: 
    run_bot() 
    time.sleep(5) 
+0

schreibe die Liste in eine Datei mit 'json.dumps' – Keatinge

Antwort

0

Was Sie suchen serialization genannt wird. Sie können json oder yaml oder sogar pickle verwenden. Sie alle haben sehr ähnlichen APIs:

import json 

a = [1,2,3,4,5] 

with open("/tmp/foo.json", "w") as fd: 
    json.dump(a, fd) 

with open("/tmp/foo.json") as fd: 
    b = json.load(fd) 

assert b == a 

foo.json:

$ cat /tmp/foo.json 
[1, 2, 3, 4, 5] 

json und yaml nur arbeiten mit Grundtypen wie Strings, Zahlen, Listen und Wörterbücher. Pickle bietet mehr Flexibilität, sodass Sie komplexere Typen wie Klassen serialisieren können. json wird im Allgemeinen für die Kommunikation zwischen Programmen verwendet, während yaml verwendet wird, wenn die Eingabe auch von Menschen bearbeitet/gelesen werden muss.

Für Ihren Fall möchten Sie wahrscheinlich json. Wenn Sie es schön machen wollen, gibt es Optionen für die Bibliothek json, um die Ausgabe einzurücken.

Verwandte Themen