How to activate different Python codes on user request? - python

beginner here.
CONTEXT: I just started coding last month. I am a translation and interpretation student, and have kind of a thesis project. I chose to create a assistive program for translators that would make things like looking up words online easier etc. I have greatly benefitted from StackOverflow and similar sites in creating a few codes that work well -for a beginner at least.
What I need is a way to combine my small codes into one bigger program in which the user can choose which function of my project they would like to use. I have, for example, a timer that gives the user notification to take a break in given intervals and an integrated API for machine translation.
I looked online for similar problems but they did not include commands for working on user demand. What I have in my mind is a program that works like:
When you run the code, it asks you "Which tool would you like to use? Translation or timer?" and runs the appropriate command on user demand. Here are my two codes for example: First is my machine translation API and the latter is my notification timer.
import requests
print('Welcome to the translation tool. Below are some language codes for you to use:')
print('English -> en, Turkish -> tr, Spanish -> es, French -> fr, Russian -> ru, Chinese -> zh.')
print('***You can type "e" into the source word box to exit the program.***')
sourcelang = str(input('Which language would you like to translate FROM?: '))
targetlang = str(input('Which language would you like to translate TO?: '))
while 1==1:
url = "https://systran-systran-platform-for-language-processing-v1.p.rapidapi.com/translation/text/translate"
word = str(input('Which word would you like to look up?: '))
querystring = {"source":sourcelang, "target":targetlang, "input":word}
headers = {
'x-rapidapi-key': "8a96426f46msh7c7b8957d8b6d49p12c046jsnf7904623bf34",
'x-rapidapi-host': "systran-systran-platform-for-language-processing-v1.p.rapidapi.com"
}
response = requests.request("GET", url, headers=headers, params=querystring)
print(response.text)
if word == str('e'):
print ('Thanks for using this software. Have a good one.')
break
and
import winrt.windows.ui.notifications as notifications
import winrt.windows.data.xml.dom as dom
import time
userinput = input('Specify time intervals in minutes: ')
print('Timer started, will notify to take a break in specified intervals.')
while 1 == 1:
notifString = """
<toast>
<visual>
<binding template='ToastGeneric'>
<text>Time to Get Up</text>
<text>Stretch Your Legs</text>
</binding>
</visual>
</toast>
"""
notifTime = float(userinput)
notifManager = notifications.ToastNotificationManager
notif = notifManager.create_toast_notifier()
xmlNotif = dom.XmlDocument()
xmlNotif.load_xml(notifString)
def givenotification(t) :
time.sleep(t*60)
notif.show(notifications.ToastNotification(xmlNotif))
givenotification(notifTime)
Please do let me know if my question is too vague or you need some more details. Thanks in advance.
P.S: Additional help to make my code and program look better would be much appreciated :)

You can use the execfile('filename.py') in Python2
or
You can use the exec(open('filename.py').read()) in Python3
import os
choice=input("Which tool would you like to use? Translation or timer?")
if choice.lower() == "translation":
exec(open('translation.py').read())
elif choice.lower() == "timer":
exec(open('timer.py').read())
else:
print("Only 2 options available(Translation/Timer")
Or you can simply import the another translation and timer file as a module and execute their functions in the if else block

You could just wrap both the tools into their own methods, then give the user the choice at the start of the program (in main() with this example):
import requests
import winrt.windows.ui.notifications as notifications
import winrt.windows.data.xml.dom as dom
import time
def Translate():
print('Welcome to the translation tool. Below are some language codes for you to use:')
print('English -> en, Turkish -> tr, Spanish -> es, French -> fr, Russian -> ru, Chinese -> zh.')
print('***You can type "e" into the source word box to exit the program.***')
sourcelang = str(input('Which language would you like to translate FROM?: '))
if word == str('e'):
print ('Thanks for using this software. Have a good one.')
break
targetlang = str(input('Which language would you like to translate TO?: '))
while 1==1:
url = "https://systran-systran-platform-for-language-processing-v1.p.rapidapi.com/translation/text/translate"
word = str(input('Which word would you like to look up?: '))
querystring = {"source":sourcelang, "target":targetlang, "input":word}
headers = {
'x-rapidapi-key': "8a96426f46msh7c7b8957d8b6d49p12c046jsnf7904623bf34",
'x-rapidapi-host': "systran-systran-platform-for-language-processing-v1.p.rapidapi.com"
}
response = requests.request("GET", url, headers=headers, params=querystring)
print(response.text)
def givenotification(t) :
time.sleep(t*60)
notif.show(notifications.ToastNotification(xmlNotif))
def Timer():
userinput = input('Specify time intervals in minutes: ')
print('Timer started, will notify to take a break in specified intervals.')
while 1 == 1:
notifString = """
<toast>
<visual>
<binding template='ToastGeneric'>
<text>Time to Get Up</text>
<text>Stretch Your Legs</text>
</binding>
</visual>
</toast>
"""
notifTime = float(userinput)
notifManager = notifications.ToastNotificationManager
notif = notifManager.create_toast_notifier()
xmlNotif = dom.XmlDocument()
xmlNotif.load_xml(notifString)
givenotification(notifTime)
def main():
choice = ''
while choice != '3':
choice = input('Which tool would you like to use? 1->Translate, 2->Timer, 3->Quit')
if choice == '1':
Translate()
elif choice == '2':
Timer()
main()
I also moved the if word == str('e): up so you don't have to wait for a http request just to quit the program.

You can run a file using os module. You can use that and if else block to check user input and run the file you want to. Here is an example:
import os
choice=input("Which tool would you like to use? Translation or timer?")
if choice.lower() == "translation":
os.startfile("Translation.py")#Your file path here
elif choice.lower() == "timer":
os.startfile("Timer.py")
else:
print("Only 2 options available(Translation/Timer")

Related

how to add submit button in streamlit (The button inside a button seems to reset the whole app.Why?)

when i click answer button it refreshing whole app. please see this link for what i am exactly expecting https://youtu.be/WO2mK1VnlZU. just download SessionState.py file from this link(adapted from https://gist.github.com/tvst/036da038ab3e999a64497f42de966a92 93) to import SessionState Thanks in advance
import streamlit as st
import SessionState
import random
import operator
def random_problem():
st.markdown("<h1 style = 'text-align:center; color:green;'>Simple Math</h1>", unsafe_allow_html=True)
session_state = SessionState.get(name = "", button_start = False)
session_state.name = st.text_input("Enter Your Name")
button_start = st.button('Start Game')
if button_start:
session_state.button_start = True
if session_state.button_start:
st.write("Welcome ", session_state.name)
session_state.operators = {
'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'/': operator.truediv,
}
session_state.num1 = random.randint(1,10)
session_state.num2 = random.randint(1,10)
session_state.operation = random.choice(list(session_state.operators.keys()))
session_state.answer = session_state.operators.get(session_state.operation)(session_state.num1,session_state.num2)
st.write('What is:', session_state.num1, session_state.operation, session_state.num2,'?')
session_state.ans = st.text_input('Answer: ')
session_state.button_submit = st.button('Answer')
if session_state.button_submit:
if session_state.answer == session_state.ans:
st.write('Correct')
else:
st.write('Incorrect')
random_problem()
```[![when i click answer button it keep on refreshing whole app][1]][1]
[1]: https://i.stack.imgur.com/IowEQ.png
That`s how streamlit works - every time you change your choice (for example click on a button) it runs the whole script again.
But - you can use caching in order to cache things that you have to calculate again and again.
Please read here about caching in streamlit - https://docs.streamlit.io/en/stable/caching.html
For future references, Streamlit now have forms which will wait to run the codes until form submit button is pressed.
with st.form("key1"):
# ask for input
button_check = st.form_submit_button("Button to Click")
# do something to calculate. Will not run until button is clicked.
See the blog post by Streamlit. https://blog.streamlit.io/introducing-submit-button-and-forms/

Python | use a printed value before

i'm actually trying to dev a slack bot with python. I'm learning python and slack api at the same time and i want to know how can i use a value printed before ?
import os
from slackeventsapi import SlackEventAdapter
from slack import WebClient
from slack.errors import SlackApiError
import time
client = WebClient(token=os.environ['SLACK_KEY'])
response = client.chat_postMessage(
channel='starterbot',
text="Hello, are you there ?")
assert response["message"]["text"] == "Hello, are you there ?"
RTM_READ_DELAY = 2
time.sleep(RTM_READ_DELAY)
print(response['ts'])
# if response == "Yes":
# elif response != "Yes":
# client.chat_postMessage(
# channel='starterbot',
# text="Bye!")
if client.conversations_replies(channel='C01665VJ2JH', ts='1593523175.013300') == "Yes":
client.chat_postMessage(channel='starterbot', text="u sure ?")
i want to create a variable to save the ts value that i print, and then use it in the client.conversations_replies.
Ty for your help

Python on Visual Studio Error

Can somebody help me identify the error here? I am using Python on Visual Studio, and I have copied the code from another source. When I paste the code into a playground like Ideone.com, the program runs without issue. Only when I paste into visual studio do I get an error. The error is in the last two lines of code that begin with "print". This is probably a huge noob question, but I am a beginner. Help!
import hashlib as hasher
import datetime as date
# Define what a Snakecoin block is
class Block:
def __init__(self, index, timestamp, data, previous_hash):
self.index = index
self.timestamp = timestamp
self.data = data
self.previous_hash = previous_hash
self.hash = self.hash_block()
def hash_block(self):
sha = hasher.sha256()
sha.update(str(self.index) + str(self.timestamp) + str(self.data) + str(self.previous_hash))
return sha.hexdigest()
# Generate genesis block
def create_genesis_block():
# Manually construct a block with
# index zero and arbitrary previous hash
return Block(0, date.datetime.now(), "Genesis Block", "0")
# Generate all later blocks in the blockchain
def next_block(last_block):
this_index = last_block.index + 1
this_timestamp = date.datetime.now()
this_data = "Hey! I'm block " + str(this_index)
this_hash = last_block.hash
return Block(this_index, this_timestamp, this_data, this_hash)
# Create the blockchain and add the genesis block
blockchain = [create_genesis_block()]
previous_block = blockchain[0]
# How many blocks should we add to the chain
# after the genesis block
num_of_blocks_to_add = 20
# Add blocks to the chain
for i in range(0, num_of_blocks_to_add):
block_to_add = next_block(previous_block)
blockchain.append(block_to_add)
previous_block = block_to_add
# Tell everyone about it!
print "Block #{} has been added to the blockchain!".format(block_to_add.index)
print "Hash: {}\n".format(block_to_add.hash)
In visual studio and most other editors, they are updated to the most recent python, also meaning that you have to place parentheses after the print statement.
For example:
print("hello")
Visual Studio runs Python 3.x.x, so, you have to write the print sentences on this way:
print('String to print')
Because in Python 3 print is a function, not a reserved word like in Python 2.

updating tkinter window (Python 3.4)

Good Afternoon all,
I've been working on a contact-book program for a school project. I've got all of the underlying code complete. However I've decided to take it one step further and implement a basic interface. I am trying to display all of the contacts using the code snippet below:
elif x==2:
phonebook_data= open(data_path,mode='r',encoding = 'utf8')
if os.stat(data_path)[6]==0:
print("Your contact book is empty.")
else:
for line in phonebook_data:
data= eval(line)
for k,v in sorted(data.items()):
x= (k + ": " + v)
from tkinter import *
root = Tk()
root.title("Contacts")
text = Text(root)
text.insert('1.0', x)
text.pack()
text.update()
root.mainloop()
phonebook_data.close()
The program works, however every contact opens in a new window. I would like to display all of the same information in a single loop. I'm fairly new to tkinter and I apologize if the code is confusing at all. Any help would be greatly appreciated!!
First of all, the top of the snippet could be much more efficient:
phonebook_data= open(data_path,mode='r',encoding = 'utf8') should be changed to
phonebook_data = open(data_path).
Afterwards, just use:
contents = phonebook_data.read()
if contents == "": # Can be shortened to `if not contents:`
print("Your contact book is empty.")
And by the way, it's good practice to close the file as soon as you're done using it.
phonebook_data = open(data_path)
contents = phonebook_data.read()
phonebook_data.close()
if contents == "":
print("Your contact book is empty.")
Now for your graphics issue. Firstly, you should consider whether or not you really need a graphical interface for this application. If so:
# Assuming that the contact book is formatted `Name` `Number` (split by a space)
name_number = []
for line in contents.split("\n"): # Get each line
name, number = line.split()
name_number.append(name + ": " + number) # Append a string of `Name`: `Number` to the list
name_number.sort() # Sort by name
root = Tk()
root.title("Contact Book")
text = Text(root)
text.pack(fill=BOTH)
text.insert("\n".join(name_number))
root.mainloop()
Considering how much I have shown you, it would probably be considered cheating for you to use it. Do some more research into the code though, it didn't seem like the algorithm would work in the first place.

BeautifulSoup in Python not parsing right

I am running Python 2.7.5 and using the built-in html parser for what I am about to describe.
The task I am trying to accomplish is to take a chunk of html that is essentially a recipe. Here is an example.
html_chunk = "<h1>Miniature Potato Knishes</h1><p>Posted by bettyboop50 at recipegoldmine.com May 10, 2001</p><p>Makes about 42 miniature knishes</p><p>These are just yummy for your tummy!</p><p>3 cups mashed potatoes (about<br> 2 very large potatoes)<br>2 eggs, slightly beaten<br>1 large onion, diced<br>2 tablespoons margarine<br>1 teaspoon salt (or to taste)<br>1/8 teaspoon black pepper<br>3/8 cup Matzoh meal<br>1 egg yolk, beaten with 1 tablespoon water</p><p>Preheat oven to 400 degrees F.</p><p>Sauté diced onion in a small amount of butter or margarine until golden brown.</p><p>In medium bowl, combine mashed potatoes, sautéed onion, eggs, margarine, salt, pepper, and Matzoh meal.</p><p>Form mixture into small balls about the size of a walnut. Brush with egg yolk mixture and place on a well-greased baking sheet and bake for 20 minutes or until well browned.</p>"
The goal is to separate out the header, junk, ingredients, instructions, serving, and number of ingredients.
Here is my code that accomplishes that
from bs4 import BeautifulSoup
def list_to_string(list):
joined = ""
for item in list:
joined += str(item)
return joined
def get_ingredients(soup):
for p in soup.find_all('p'):
if p.find('br'):
return p
def get_instructions(p_list, ingredient_index):
instructions = []
instructions += p_list[ingredient_index+1:]
return instructions
def get_junk(p_list, ingredient_index):
junk = []
junk += p_list[:ingredient_index]
return junk
def get_serving(p_list):
for item in p_list:
item_str = str(item).lower()
if ("yield" or "make" or "serve" or "serving") in item_str:
yield_index = p_list.index(item)
del p_list[yield_index]
return item
def ingredients_count(ingredients):
ingredients_list = ingredients.find_all(text=True)
return len(ingredients_list)
def get_header(soup):
return soup.find('h1')
def html_chunk_splitter(soup):
ingredients = get_ingredients(soup)
if ingredients == None:
error = 1
header = ""
junk_string = ""
instructions_string = ""
serving = ""
count = ""
else:
p_list = soup.find_all('p')
serving = get_serving(p_list)
ingredient_index = p_list.index(ingredients)
junk_list = get_junk(p_list, ingredient_index)
instructions_list = get_instructions(p_list, ingredient_index)
junk_string = list_to_string(junk_list)
instructions_string = list_to_string(instructions_list)
header = get_header(soup)
error = ""
count = ingredients_count(ingredients)
return (header, junk_string, ingredients, instructions_string,
serving, count, error)
It works well except in situations where I have chunks that contain strings like "Sauté" because soup = BeautifulSoup(html_chunk) causes Sauté to turn into Sauté and this is a problem because I have a huge csv file of recipes like the html_chunk and I'm trying to structure all of them nicely and then get the output back into a database. I tried checking it Sauté comes out right using this html previewer and it still comes out as Sauté. I don't know what to do about this.
What's stranger is that when I do what BeautifulSoup's documentation shows
BeautifulSoup("Sacré bleu!")
# <html><head></head><body>Sacré bleu!</body></html>
I get
# Sacré bleu!
But my colleague tried that on his Mac, running from terminal, and he got exactly what the documentation shows.
I really appreciate all your help. Thank you.
This is not a parsing problem; it is about encoding, rather.
Whenever working with text which might contain non-ASCII characters (or in Python programs which contain such characters, e.g. in comments or docstrings), you should put a coding cookie in the first or - after the shebang line - second line:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
... and make sure this matches your file encoding (with vim: :set fenc=utf-8).
BeautifulSoup tries to guess the encoding, sometimes it makes a mistake, however you can specify the encoding by adding the from_encoding parameter:
for example
soup = BeautifulSoup(html_text, from_encoding="UTF-8")
The encoding is usually available in the header of the webpage

Categories