How to use the most recently printed line as an input? - python

I am trying to create a Twitter bot that posts a random line from a text file. I have gone as far as generating the random lines, which print one at a time, and giving the bot access to my Twitter app, but I can't for the life of me figure out how to use a printed line as a status.
I am using Tweepy. My understanding is that I need to use api.update_status(status=X), but I don't know what X needs to be for the status to match the most recently printed line.
This is the relevant section of what I have so far:
from random import choice
x = 1
while True:
file = open('quotes.txt')
content = file.read()
lines = content.splitlines()
print(choice(lines))
api.update_status(status=(choice(lines)))
time.sleep(3600)
The bot is accessing Twitter no problem. It is currently posting another random quote generated by (choice(lines)), but I'd like it to match what prints immediately before.

I may not fully understand your question, but from the very top, where it says, "How to use the most recently printed line as an input", I think I can answer that. Whenever you use the print() command, store the argument into a string variable that overwrites its last value. Then it saves the last printed value.

Instead of directly printing a choice:
print(choice(lines))
create a new variable and use it in your print() and your api.update_status():
selected_quote = choice(lines)
print(selected_quote)
api.update_status(status=selected_quote)

Related

Question about using dictionaries other than using Counter(email_lst).most_common()

I have a question regarding my python programming. Before I ask a question, here is the instructions that I have to complete:
[Write a program to read through the example_messages.txt file and figure out who has sent the greatest number of mail messages.
The program looks for 'From ' lines and takes the second word of those lines as the person who sent the mail. The program creates a Python dictionary that maps the sender's mail address to a count of the number of times they appear in the file.]
I attached a PDF file URL of the kind of program that I created. I also tried to attach the "example_messages" text file to Stack Overflow but wouldn't let me. So instead, I attached a photo instead.
[Program that I created] https://ibb.co/nm3dBYt
[Photo of example_messages.txt] https://ibb.co/qkmfrLn
I used the “Counter(email_lst).most_common()” function in my program to complete the task. This method works, but based on the assignment, I have to use the dictionary to complete the task, and I am having a difficult time coming up with any ideas when using dictionaries. The program should be no more than 10 lines of code. Does anyone have any ideas or suggestions?
Best Regards
You can "manually" add 1 to entries in the dictionary and use the max() function at the end to get the entry with the highest count:
counts = dict()
with open('example_messages.txt') as f:
for line in f.readlines():
if not line.stastswith("From"): continue
email = line.split()[1]
counts[email] = counts.get(email,0) + 1
email,count = max(counts.items(),key=lambda ec:ec[1])
print(email,"hase themost sent emails which is",count)

Issue with a python string loop

So I'm having trouble getting my code to use a list of strings as inputs in a loop. Here's roughly what I have so far.
from arcgis.gis import GIS
Users = ['User01','User02','User03']
User_string = str(Users) # Have to do this as code needs input as string
gis = GIS("https://www.arcgis.com","USERNAME","PASSWORD") # This logs you into ArcGIS Online
User_role = 'org_user'
for x in User_string:
test = gis.users.get(username=x)
test.update_role(role=User_role)
print("Done! Check Web")
I just can't get the loop to work right. When I remove the for loop and put each user name in individually the get user and update role commands work just fine, it's just in the loop that is broken.
The two errors I'm getting is that the username has to be a string. I fixed that by adding the str() command, but I can't get the username to enter into the user.get loop.
Any suggestions? This code is actually looking at an excel file to produce the list of usernames so I can't just hardcode the list into the code. If it helps at all the website I've been using for the ArcGIS portion of the code is this one: https://developers.arcgis.com/python/guide/accessing-and-managing-users/
I should mention that I also tried just printing
test=gis.users.get(username=User_string)
And it came back as None. So I guess my question is how do I get 'User01' to go into the username=x spot?
Thanks much!
You're doing a for with the list as a string so it's looping on each character of the string. You need to do it with the original list.
Based on your code, you are telling your for loop to iterate on a String, since you converted your list to a string with User_string = str(Users); So the loop is going over each character on the string, which now it is User01User02User03
What you need to do is to iterate the list Users, like:
from arcgis.gis import GIS
Users = ['User01','User02','User03']
gis = GIS("https://www.arcgis.com","USERNAME","PASSWORD") # This logs you into ArcGIS Online
User_role = 'org_user'
for x in Users:
test = gis.users.get(username=x)
test.update_role(role=User_role)
print("Done! Check Web")

Program doesn't append file using variables, but no error message appears

Using Python 3.4.2
I'm working on a quiz system using python. Though it hasn't been efficient, it has been working till now.
Currently, I have a certain user log in, take a quiz, and the results of the quiz get saved to a file for that users results. I tried adding in so that it also saves to a file specific to the subject being tested, but that's where the problem appears.
user_score = str(user_score)
user_score_percentage_str = str(user_score_percentage)
q = open('user '+(username)+' results.txt','a')
q.write(test_choice)
q.write('\n')
q.write(user_score+'/5')
q.write('\n')
q.write(user_score_percentage_str)
q.write('\n')
q.write(user_grade)
q.write('\n')
q.close()
fgh = open(test_choice+'results.txt' ,'a')
fgh.write(username)
fgh.write('\n')
fgh.write(user_score_percentage_str)
fgh.write('\n')
fgh.close
print("Your result is: ", user_score , "which is ", user_score_percentage,"%")
print("Meaning your grade is: ", user_grade)
Start()
Everything for q works (this saves to the results of the user)
However, once it comes to the fgh, the thing doesn't work at all. I receive no error message, however when I go the file, nothing ever appears.
The variables used in the fgh section:
test_choice this should work, since it worked for the q section
username, this should also work since it worked for the q section
user_score_percentage_str and this, once more, should work since it worked for the q section.
I receive no errors, and the code itself doesn't break as it then correctly goes on to print out the last lines and return to Start().
What I would have expected in the file is to be something like:
TestUsername123
80
But instead, the file in question remains blank, leading me to believe there must be something I'm missing regarding working the file.
(Note, I know this code is unefficient, but except this one part it all worked.)
Also, apologies if there's problem with my question layout, it's my first time asking a question.
And as MooingRawr kindly pointed out, it was indeed me being blind.
I forgot the () after the fgh.close.
Problem solved.

Python overwriting variable in script 1 with user input from script2

I've been struggling with this for several days now, and I cant find any answers that actually relate to what I'm trying to do, at least none that I can find.
I am trying to create a basic system for keeping track of my finances (i.e. cash, whats in the bank, etc). I have two scripts: display.py and edit.py.
The idea is that I can easily pull up display.py and see how much I have and where it is, and use edit.py to change the amounts shown in display.py, without having to open Vi or entering the numbers every time i run display.py.
In theory, edit.py would take user input, and then overwrite the value in display with that new input, so that display is independent of edit and saves those values
display.py:
cash1 = "5.14"
bank1 = "none"
print "you have", cash1, "in your pocket"
print ""
print ""you have", bank1, "in the bank"
and using this in edit.py
f = open("display.py", "r")
contents = f.readlines()
f.close()
cashinput1 = "cash1"
cashinput2 = raw_input("enter the new coin amount: ")
cashtransfer = ("=".join((cashinput1,cashinput2,)))
contents.insert(5, cashtransfer)
f = open("display.py", "w")
contents = "".join(contents)
f.write(contents)
f.close()
I know edit.py isn't very clean, but the problem is that it's adding the input to the end of a line, pushing it to the next one. The goal is overwrite cash1, not add another. I've tried simply importing, but that doesn't work as the changes aren't saved.
tl;dr How do I overwrite a variable in one script with user input from another script?
I'm using Python 2.7.12
thanks in advance.
EDIT: Sqlite3 looks designed for this type of thing, so this question is answered. Not sure how to close this without any answers though.
As I've been pointed toward Sqlite3, I will use that. Thanks again, question answered :)

Getting input constantly using python multithreading

I want to write a program which will print a string every second on the other hand it will allow user to write text, I have the code snippet below. My problem is everytime a new line is printed, input line is also disturbed. Is there a way to seperate the output lines from the input line?
import time
from thread import start_new_thread
def heron():
while 1:
time.sleep(1)
print "some text"
start_new_thread(heron,())
c = raw_input("Enter text>")
I doubt you can do this without curses. There might be another way, but I don't think it would be very pretty. There's a basic how-to here.

Categories

Resources