Python将变量从文件加载到数组中

时间:2016-06-09 21:54:50

标签: python arrays reddit praw

我正在制作一个reddit机器人并且我已经将注释ID存储在一个数组中,因此它不会两次回复相同的注释,但是如果我关闭程序,则数组是清零。

我正在寻找一种方法来保存数组,例如将其存储在外部文件中并阅读它,谢谢!

这是我的代码:

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)

1 个答案:

答案 0 :(得分: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往往在人类需要编辑/读取输入时使用。{/ p>

对于您的情况,您可能需要json。如果你想使它漂亮,json库可以选择缩进输出。