2016-06-09 73 views
0

我正在製作一個reddit機器人,並且它已將它存儲在數組中,因此它不會回覆相同的註釋兩次,但是如果關閉程序數組被清除。Python將變量從文件加載到數組中

我正在尋找一種方法來保持數組,例如將其存儲在外部文件中並閱讀它,謝謝!

這裏是我的代碼:

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

用'json.dumps'將列表寫入文件 – Keatinge

回答

0

你在尋找什麼叫serialization。您可以使用jsonyaml甚至pickle。他們都有着非常相似的API:

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] 

jsonyaml只有基本類型,如字符串,數字,列表和字典的工作。 Pickle具有更多的靈活性,允許您序列化更復雜的類型,如類。 json通常用於程序之間的通信,而yaml傾向於在輸入需要人工編輯/讀取時使用。您可能需要json。如果你想讓它變得漂亮,可以選擇json庫來縮進輸出。