Question

For my computer class I have to create a program that deals with making and searching tweets. I am done with the program but keep getting the error below when I try the first option in the shell. Can someone please explain this error and show me how to fix it in my code below? Thanks!

twitter.py - C:/Users/Owner/AppData/Local/Programs/Python/Python38/twitter.py (3.8.3) File Edit Format Run Options Window Heltwitter.py - C:/Users/Owner/AppData/Local/Programs/Python/Python38/twitter.py (3.8.3) File Edit Format Run Options Window HelTweet.py - C:/Users/Owner/AppData/local/Programs/Python/Python38/Twe... File Edit Format Run Options Window Help import timePython 3.8.3 Shell File Edit Shell Debug Options Window Help Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:37:02) [MSC v

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Working code implemented in Python and appropriate comments provided for better understanding:

Here I am attaching code for these files:

  • Twitter.py
  • Tweet.py

Source code for Twitter.py:

# twitter.py

import Tweet, pickle

def main():

tweet_file_name = "tweets.dat"
tweets = load_tweets(tweet_file_name)
  
while (True):
print_menu()
choice = get_menu_choice()

# Make a Tweet
if (choice == 1):
create_tweet(tweets)
save_tweets(tweet_file_name, tweets)
  
# View Recent Tweets
elif (choice == 2):
view_recent_tweets(tweets, 5)
  
# Search Tweets
elif (choice == 3):
search_tweets(tweets)
  
# Exit
else:
print("\nThank you for using the Tweet Manager!")
break

def load_tweets(tweet_file_name):
try:
# Attempt to open tweet_file_name
tweet_file = open(tweet_file_name, "rb")
tweets = pickle.load(tweet_file)
tweet_file.close()
except:
# If tweet_file_name cannot be loaded, start with an empty list
tweets = []

# Return Tweet list
return tweets

def save_tweets(tweet_file_name, tweets):
try:
# Attempt to save the Tweet list
output_file = open(tweet_file_name, "wb")
pickle.dump(tweets, output_file)
output_file.close()
except:
print("Error: The Tweets could not be saved.")

def print_menu():
# Print the Tweet Menu
print("\nTweet Menu")
print("----------")
print("1. Make a Tweet")
print("2. View Recent Tweets")
print("3. Search Tweets")
print("4. Quit")

def get_menu_choice():
# Prompt for a choice and validate it
while (True):
try:
choice = int(input("\nWhat would you like to do? "))
if (choice < 1 or choice > 4):
print("Please select a valid option.")
continue
except:
print("Please enter a numeric value.")
else:
break

return choice

def create_tweet(tweets):
# Ask for the user's name
name = input("\nWhat is your name? ")
  
while (True):
# Ask for the user's message
text = input("What would you like to tweet? ")

# If the tweet is too long, display an error and ask again
if (len(text) > 140):
print("\nTweets can only be 140 characters!\n")
else:
# ...otherwise, the tweet is <140 characters, so stop looping
break

# Create a Tweet object using the user's name and message
tweet = Tweet.Tweet(name, text)

# Add the Tweet to the tweets list
tweets.append(tweet)

# Print a confirmation that the Tweet has been made
print(name, ", your tweet has been saved.", sep="")

def view_recent_tweets(tweets, count):
print("\nRecent Tweets")
print("-------------")

# Check if there are any Tweets
if (len(tweets) < 1):
print("There are no recent tweets.")
else:
# If there are Tweets, get the five most recent and reverse their order
reordered_last_five_tweets = reversed(tweets[-5:])

# Loop through and print the recent Tweets
for tweet in reordered_last_five_tweets:
print_tweet(tweet)

def search_tweets(tweets):
# Check if there are any Tweets
if (len(tweets) < 1):
print("\nThere are no tweets to search.")
else:
# Ask the user for a search term
search_term = input("\nWhat would you like to search for? ")

print("\nSearch Results")
print("--------------")

# Reorder the Tweets to show the most recent first
reordered_tweets = reversed(tweets)
found_term = False

# Loop through the Tweets
for tweet in reordered_tweets:
# Look for the search term in each Tweet's text
if (search_term in tweet.get_text()):
print_tweet(tweet)
found_term = True

if (not found_term):
print("No tweets contained", search_term)


def print_tweet(tweet):
print(tweet.get_author(), "-", tweet.get_age())
print("", tweet.get_text(), "\n")
  


# Call main
main()

Code Screenshots:

# twitter.py import Tweet, pickle def main(): tweet_file_name = tweets.dat tweets = load_tweets(tweet_file_name) while (Tru

61 # Print the Tweet Menu 62 print(\nTweet Menu) 63 print(----------) 64 print(1. Make a Tweet) se 65 print(2. View Re

else: # If there are Tweets, get the five most recent and reverse their order reordered_last_five_tweets = reversed(tweets[-5

Source code for Tweet.py:

# Tweet.py
# Defines Tweet class

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):
# What is the current time?
now = time.time()
  
# How many seconds, minutes, and hours have passed since tweet?
seconds = now - self.__age
minutes = seconds // 60
hours = seconds // 3600
  
# Return most significant bit
if (hours > 0):
return str(int(hours)) + "h"
elif (minutes > 0):
return str(int(minutes)) + "m"
else:
return str(int(seconds)) + "s"

Code Screenshots:

1 # Tweet.py 2 # Defines Tweet class 3 4 import time 5 6 class Tweet: 7 def _init_(self, author, text): 8 self._author author

Sample Output Screenshots:

x Tweet Menu 1. Make a Tweet 2. View Recent Tweets 3. Search Tweets 4. Quit What would you like to do? 1 What is your name? S

Tweet Menu 1. Make a Tweet 2. View Recent Tweets 3. Search Tweets 4. Quit What would you like to do? 2 Recent Tweets David 11

Hope it helps, if you like the answer give it a thumbs up. Thank you.

Add a comment
Know the answer?
Add Answer to:
For my computer class I have to create a program that deals with making and searching...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Python 3+ Adjust the following code so the two errors below are non-present: 1. __init__() :...

    Python 3+ Adjust the following code so the two errors below are non-present: 1. __init__() : Since Pizza object don't have it's own set() datastructure, the toppings in the pizza object are manimupated from out of the object. (-1.0) 2. __eq__() : How about "self.toppings == other.toppings" rather than "self.toppings - other.toppin == set())". Code: ## Program 1 ## --------------------------------- class Pizza: def __init__(self, s='M', top=set()): self.setSize(s) self.toppings = top def setSize(self, s): self.size = s def getSize(self): return self.size...

  • I am currently facing a problem with my python program which i have pasted below where...

    I am currently facing a problem with my python program which i have pasted below where i have to design and implement python classes and record zoo database and takes user input as query. the error i am recieving says that in line 61 list index is out of range. kindly someone help me with it as soon as possible. Below is the program kindly check and correct it. Thanks! class Animal: def __init__(self, name, types, species, mass): self.name=name self.type=types...

  • I'm making a To-Do list in Python 2 and had the program running before remembering that...

    I'm making a To-Do list in Python 2 and had the program running before remembering that my professor wants me to put everything in procedures. I can't seem to get it to work the way I have it now and I can't figure it out. I commented out the lines that was originally in the working program and added procedures to the top. I've attached a screenshot of the error & pasted the code below. 1 todo_list = [] 2...

  • I am currently facing a problem with my python program which i have pasted below where i have to design and implement python classes and record zoo database and takes user input as query. the error i...

    I am currently facing a problem with my python program which i have pasted below where i have to design and implement python classes and record zoo database and takes user input as query. the error i am recieving says that in line 61 list index is out of range. kindly someone help me with it as soon as possible. Below is the program kindly check and correct it. Thanks! class Animal: def __init__(self, name, types, species, mass): self.name=name self.type=types...

  • I have to write a program where the program prints a deck of cards. instead of having your regula...

    I have to write a program where the program prints a deck of cards. instead of having your regular suits and numbers the program will use a value for a number, id will be either rock, paper, or scissors, and the coin will be heads or tails. print example: 2 of rock heads. If the user is enters 1 the program will print out 30 of the print example and arrange them by there values. if the user enters 2...

  • I am having trouble with my Python code in this dictionary and pickle program. Here is...

    I am having trouble with my Python code in this dictionary and pickle program. Here is my code but it is not running as i am receiving synthax error on the second line. class Student: def__init__(self,id,name,midterm,final): self.id=id self.name=name self.midterm=midterm self.final=final def calculate_grade(self): self.avg=(self.midterm+self.final)/2 if self.avg>=60 and self.avg<=80: self.g='A' elif self.avg>80 and self.avg<=100: self.g='A+' elif self.avg<60 and self.avg>=40: self.g='B' else: self.g='C' def getdata(self): return self.id,self.name.self.midterm,self.final,self.g CIT101 = {} CIT101["123"] = Student("123", "smith, john", 78, 86) CIT101["124"] = Student("124", "tom, alter", 50,...

  • PYTHON. Continues off another code. I don't understand this. Someone please help! Comment the lines please...

    PYTHON. Continues off another code. I don't understand this. Someone please help! Comment the lines please so I can understand LinkedList ADT: class myLinkedList:     def __init__(self):         self.__head = None         self.__tail = None         self.__size = 0     def insert(self, i, data):         if self.isEmpty():             self.__head = listNode(data)             self.__tail = self.__head         elif i <= 0:             self.__head = listNode(data, self.__head)         elif i >= self.__size:             self.__tail.setNext(listNode(data))             self.__tail = self.__tail.getNext()         else:             current = self.__getIthNode(i - 1)             current.setNext(listNode(data,...

  • 9p This is for Python I need help. Pet #pet.py mName mAge class Pet: + __init__(name,...

    9p This is for Python I need help. Pet #pet.py mName mAge class Pet: + __init__(name, age) + getName + getAge0 def init (self, name, age): self.mName = name self.mAge = age Dog Cat def getName(self): return self.mName mSize mColor + __init__(name, age,size) + getSize() + momCommento + getDog Years() +_init__(name, age,color) + getColor + pretty Factor + getCatYears def getAge(self): return self.mAge #dog.py import pet #cat.py import pet class Dog (pet. Pet): class Cat (pet. Pet): def init (self,...

  • in python and according to this #Creating class for stack class My_Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def Push(self, d): self.items.append(d) def Po...

    in python and according to this #Creating class for stack class My_Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def Push(self, d): self.items.append(d) def Pop(self): return self.items.pop() def Display(self): for i in reversed(self.items): print(i,end="") print() s = My_Stack() #taking input from user str = input('Enter your string for palindrome checking: ') n= len(str) #Pushing half of the string into stack for i in range(int(n/2)): s.Push(str[i]) print("S",end="") s.Display() s.Display() #for the next half checking the upcoming string...

  • Please provide pseudocode for the following python program: class Student: def t(self,m1, m2, m3): tot= m1+m2+m3;...

    Please provide pseudocode for the following python program: class Student: def t(self,m1, m2, m3): tot= m1+m2+m3; average = tot/3; return average class Grade(Student): def gr(self,av): if av>90: print('A grade') elif (av<90) and (av>70): print('B grade') elif (av<70) and (av>50): print('C grade') else: print('No grade') print ("Grade System!\n") s=Student(); repeat='y' while repeat=='y': a=int(input('Enter 1st subject Grade:')) b=int(input('Enter 2nd subject Grade:')) c=int(input('Enter 3rd subject Grade:')) aver=s.t(a,b,c); g=Grade(); g.gr(aver); repeat=input("Do you want to repeat y/n=")

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT