在Python中保存信息以及检索它

时间:2015-12-07 20:32:59

标签: python python-3.x

这两个程序的目的是让twitter.py通过在Twitter.py程序中保存的5条最新推文来管理tweet.py,以便在您搜索并找到它时显示。有四个选项,发推文,查看最近的推文,搜索推文和退出。我在保存方面遇到了麻烦,因为它一直说不会发现最近的推文。我也无法搜索我的推文,但这可能与我的第一个问题相同,因为它们没有被正确保存。谢谢你的帮助!!

tweet.py

import time
class tweet:

        def __init__(self, author, text):

            self.__author = author
            self.__text = text
            self.__age = time.time()

        def get_author(self):

            return self.__author

        def get_text(self):

            return self.__text

        def get_age(self):
            now = time.time()

            difference = now - self.__time

            hours = difference // 3600

            difference = difference % 3600

            minutes = difference // 60

            seconds = difference % 60


            # Truncate units of time and convert them to strings for output
            hours = str(int(hours))
            minutes = str(int(minutes))
            seconds = str(int(seconds))

            # Return formatted units of time
            return hours + ":" + minutes + ":" + seconds

twitter.py

import tweet
import pickle

MAKE=1
VIEW=2
SEARCH=3
QUIT=4

FILENAME = 'tweets.dat'

def main():
    mytweets = load_tweets()

    choice = 0

    while choice != QUIT:
        choice = get_menu_choice()

        if choice == MAKE:
            add(mytweets)
        elif choice == VIEW:
            recent(mytweets)
        elif choice == SEARCH:
            find(mytweets)
        else:
            print("\nThanks for using the Twitter manager!")

    save_tweets(mytweets)

def load_tweets():
    try:
        input_file = open(FILENAME, 'rb')

        tweet_dct = pickle.load(input_file)

        input_file.close()

    except IOError:
        tweet_dct = {}

    return tweet_dct

def get_menu_choice():
    print()
    print('Tweet Menu')
    print("----------")
    print("1. Make a Tweet")
    print("2. View Recent Tweets")
    print("3. Search Tweets")
    print("4. Quit")
    print()


    try:
        choice = int(input("What would you like to do? "))
        if choice < MAKE or choice > QUIT:
            print("\nPlease select a valid option.")

    except ValueError:
        print("\nPlease enter a numeric value.")

    return choice

def add(mytweets):

    author = input("\nWhat is your name? ")
    while True:
        text = input("what would you like to tweet? ")
        if len(text) > 140:
            print("\ntweets can only be 140 characters!")
            continue
        else:
            break




    entry = tweet.tweet(author, text)
    print("\nYour tweet has been saved!")



def recent(mytweets):

    print("\nRecent Tweets")
    print("-------------")
    if len(mytweets) == 0:
        print("There are no recent tweets. \n")
    else:
        for tweets in mytweets[-5]:
            print(tweets.get_author, "-", tweets.get_age)
            print(tweets.get_text, "\n")



def find(mytweets):
    author = input("What would you like to search for? ")
    if author in mytweets:
        print("\nSearch Results")
        print("----------------")
        print(tweet.tweet.get_author(), - tweet.tweet.get_age())
        print(tweet.tweet.get_text())
    else:
        print("\nSearch Results")
        print("--------------")
        print("No tweets contained ", author)

def save_tweets(mytweets):
    output_file = open(FILENAME, 'wb')

    pickle.dump(mytweets, output_file)

    output_file.close()

main()

2 个答案:

答案 0 :(得分:0)

twitter.py:add_tweets中,mytweets被传递到函数中,并且entry已创建,但它永远不会添加到mytweets。函数返回后,创建的entry将丢失。

答案 1 :(得分:0)

您的问题是:

  

我在保存方面遇到了麻烦,因为它一直说最近没有推文   找到。

功能add似乎没有在任何地方添加推文。它会创建一个tweet.tweet实例,但它不会对它做任何事情。

您可能想要将推文添加到mytweets

另一个问题: 您将mytweets初始化为dicionary(tweet_dct = {}),但稍后您将其用作列表(mytweets[-5])。它应该是一个开始的列表。你可能想要最后五个推文(mytweets[-5:]),而不仅仅是最后的第五个推文。

在旁注上:

你在这里不是“两个程序” - 它是两个python文件中的一个程序,或者“ modules

虽然使用 getters (像get_author这样的函数)没有任何问题,但Python中不需要它们(参见How does the @property decorator work?)。你自己帮忙并保持简单,例如:

class Tweet:
    def __init__(self, author, text):
        self.author = author
        self.text = text
        self.creation_time = time.time()

    def get_age_as_string(self):
        # your code from get_age

有时候你需要私有变量。当发生这种情况时,使用单个前导下划线(self._author),直到您完全理解双下划线的作用和原因。

Pickle可能不是在这里存储信息的最佳方式,但它是学习的良好开端。