from string import maketrans
intab = "abcdefghijklmnopqrstuvwxyz"
outtab = "nopqrstuvwxyzabcdefghijklm"
trantab = maketrans(intab, outtab)
print "Do you want to translate a random term, or a file?(Please enter file name in the code)"
RandOrFile = raw_input ("Type 1 to enter a custom term, or 2 to translate a whole file")
if RandOrFile == "1":
inputA = raw_input ("Enter a phrase to translate")
str = inputA
print str.translate(trantab);
elif RandOrFile == "2":
(Code for my program)
I am attempting to create a program which encrypts a file, and turns the letters into other letters, like an Enigma Machine (But much more simple). I have made it so that you can directly translate user entered phrases, as the top chunk of the code shows, but I cant work out how to translate already made files on the users computer.
The code is meant to go under the "elif RandOrFile == "2"" line, but I cant work out how to a) fetch the data from a specified file on a computer, and b) work out how to translate that file in the program.
I have researched, but I cant find any ways to do so. My python skills are very beginner, so if you could possibly quote relevant sources to help on this, that would also be helpful, although I have tried, i'm not really sure where to begin while looking through tutorial websites.
Related
I just started with python. My teacher gave me an assignment and I'm stuck on a project where I have to make the numbers of characters appear when someone enters their name for input command input("what is your name") I don't think I have been taught this and google is giving me a hard time when trying to look for the command. This might be Childs play to most but can anyone throw me a tip/hint?
using print(len(myVariable)) should output the number of characteres that the string has. You should familiarize yourself with python methods.
Here are some resources:
https://docs.python.org/3/library/functions.html
https://www.w3schools.com/python/ref_func_len.asp
Printing the length of a variable is very easy with Python due to the many built-in functions you can perform on strings! In this case, you would use use len(). Read about other helpful string methods in python too in order to get a head start on your class!
inputtedName = input("What is your name? ")
nameLength = len(inputtedName)
print("Your name is " + str(nameLength) + " letters.")
print(f"Your name is {nameLength} letters.")
The first print statement uses something called string concatenation to create a readable sentence using variables. The second uses f strings to make using variables in your strings even easier!
I am making a personal assistant in Python 2.7 using the modules 'wikipedia', 'wolframalpha' and 'pyttsx3'. I am making so that the user can ask a question and the computer will then search Wikipedia and Wolfram and speak the answer using Pyttsx. This all works fine but the computer takes a while to fetch the results for the question and I was wondering if it would be possible to add a simple '...loading...' message while is does this. I have added the code below and it would be great if you could respond.
import wikipedia
import wolframalpha
import pyttsx3;
engine = pyttsx3.init();
while True:
my_input = raw_input("Question: ")
try:
#wolframalpha code here
app_id = "Q2HXJ5-GYYYX6PYYP"
client = wolframalpha.Client(app_id)
res = client.query(my_input)
answer = next(res.results).text
print(answer)
engine.say(answer);
engine.runAndWait();
except:
try:
#wikipedia code here
print(wikipedia.summary(my_input))
except:
print("Sorry nothing can be found from your query")
If you want to remove Loading... after the API call is completed, you can just move the cursor to the start of that line using the escape code ESC[1000D. Note that you must use sys.stdout.write() as opposed to print here, as we want this all to happen on the same line.
import sys
// Before API Call
sys.stdout.write("Loading...")
sys.stdout.flush()
// After API Call
sys.stdout.write(u"\u001b[1000D")
print "Done! "
Note the u proceeding the double-quoted string. This is required in Python 2.x, as it includes special characters, but can be omitted in Python 3.
(By the way, the extra spaces on Done are only there so that the string is longer than Loading... so that it replaces it completely, without leaving ng... on the end)
I have not found an answer that satisfies my needs or is simple enough for me to actually understand as I'm relatively new to python!
I have a variable labelled difficulty which asks the user to input a string to state whether they want easy medium or hard mode. Unfortunately I am unable to successfully have python check the input for the words used and give them what i want, i end up with "easy is not defined" or "medium is not defined" or "hard is not defined." Is there a way for me to get round this problem? Here is a small section of my code which the problem is enclosed to:
difficulty=input("What difficulty do you wish to choose, easy,medium or hard?")
if difficulty==easy:
print("You have chosen the easy mode, your test will now begin")
print("")
elif difficulty==medium:
print("You have chosen the medium mode, your test will now begin")
else:
print("You have chosen the hard mode or tried to be funny, your test
will now begin")
You are trying to get a string from the user (input will return a string) then compare it to another string in this case 'easy' or 'medium'. Here is a link to a google dev article talking about some of the basic things you can do to strings in python.
difficulty = input("What difficulty do you wish to choose, easy,medium or hard?")
if difficulty == 'easy':
print("You have chosen the easy mode, your test will now begin")
print("")
elif difficulty == 'medium':
print("You have chosen the medium mode, your test will now begin")
else:
print("You have chosen the hard mode or tried to be funny, your test will now begin")
When you put easy or medium in your code you are telling python that they are variables (link to python variable tutorial) not strings. In this case you have not defined the easy variable yet ie: easy = 'some data'. Because you have not defined it python does not know what to do with easy it will throw an error.
First of all, fix your indentation (if it is not a problem only in your example). Second, you need to put easy, medium, and hard in either single ' or double " quotes:
difficulty=input("What difficulty do you wish to choose, easy,medium or hard?")
if difficulty=="easy":
print("You have chosen the easy mode, your test will now begin")
print("")
elif difficulty=="medium":
print("You have chosen the medium mode, your test will now begin")
else:
print("You have chosen the hard mode or tried to be funny, your test
will now begin")
If you don't put them in quotes, then you aren't comparing difficulty to the word easy, but rather to the variable called easy. This of course causes an error, since no such variable exists. The quotes however tell python to interpret easy as a string.
I have to write a program in python where the user is given a menu with four different "word games". There is a file called dictionary.txt and one of the games requires the user to input a) the number of letters in a word and b) a letter to exclude from the words being searched in the dictionary (dictionary.txt has the whole dictionary). Then the program prints the words that follow the user's requirements. My question is how on earth do I open the file and search for words with a certain length in that file. I only have a basic code which only asks the user for inputs. I'm am very new at this please help :(
this is what I have up to the first option. The others are fine and I know how to break the loop but this specific one is really giving me trouble. I have tried everything and I just keep getting errors. Honestly, I only took this class because someone said it would be fun. It is, but recently I've really been falling behind and I have no idea what to do now. This is an intro level course so please be nice I've never done this before until now :(
print
print "Choose Which Game You Want to Play"
print "a) Find words with only one vowel and excluding a specific letter."
print "b) Find words containing all but one of a set of letters."
print "c) Find words containing a specific character string."
print "d) Find words containing state abbreviations."
print "e) Find US state capitals that start with months."
print "q) Quit."
print
choice = raw_input("Enter a choice: ")
choice = choice.lower()
print choice
while choice != "q":
if choice == "a":
#wordlen = word length user is looking for.s
wordlen = raw_input("Please enter the word length you are looking for: ")
wordlen = int(wordlen)
print wordlen
#letterex = letter user wishes to exclude.
letterex = raw_input("Please enter the letter you'd like to exclude: ")
letterex = letterex.lower()
print letterex
Here's what you'd want to do, algorithmically:
Open up your file
Read it line by line, and on each line (assuming each line has one and only one word), check if that word is a) of appropriate length and b) does not contain the excluded character
What sort of control flow would this suggest you use? Think about it.
I'm not sure if you're confused about how to approach this from a problem-solving standpoint or a Python standpoint, but if you're not sure how to do this specifically in Python, here are some helpful links:
The Input and Output section of the official Python tutorial
The len() function, which can be used to get the length of a string, list, set, etc.
To open the file, use open(). You should also read the Python tutorial sec. 7, file input/output.
Open a file and get each line
Assuming your dictionary.txt has each word on a separate line:
opened_file = open('dictionary.txt')
for line in opened_file:
print(line) # Put your code here to run it for each word in the dictionary
Word length:
You can check the length of a string using its str.len() method. See the Python documentation on string methods.
"Bacon, eggs and spam".len() # returns '20' for 20 characters long
Check if a letter is in a word:
Use str.find(), again from the Python sring methods.
Further comments after seeing your code sample:
If you want to print a multi-line prompt, use the heredoc syntax (triple quotes) instead of repeated print() statements.
What happens if, when asked "how many letters long", your user enters bacon sandwich instead of a number? (Your assignment may not specify that you should gracefully handle incorrect user input, but it never hurts to think about it.)
My question is how on earth do I open the file
Use the with statement
with open('dictionary.txt','r') as f:
for line in f:
print line
and search for words with a certain length in that file.
First, decide what is the length of the word you want to search.
Then, read each line of the file that has the words.
Check each word for its length.
If it matches the length you are looking for, add it to a list.
For practice, I'm trying to do some stuff in Python. I've decided to make a simple hangman game - I'm not making a GUI. The game would start with a simple input(). Now, I'd like next line to, beside asking for input, to delete the hidden word. I've tried using \b (backspace character), but it's not working. Something like:
word = input("Your word: ")
for i in range(len(word) + 12):
print("\b")
Now, printing the backlash character is supposed to delete the input and "Your word", but it isn't doing anything. If I do this in IDLE I get squares, and I get nothing if I open it by clicking.
How to accomplish this? I'm afraid I wasn't too clear with my question, but I hope you'll see what I meant. :)
\b does not erase the character before the cursor, it simply moves the cursor left one column. If you want text entry without echoing the characters then look at getpass.
I assume the player entering the word wants to be sure they've entered it correctly so you probably want to display the word as they're typing it right?
How about printing enough \ns to move it off the screen when they're done or issue a clear screen command?
You mentioned this was a simple game so a simple solution seems fitting.
[Edit] Here's a simple routine to clear the console on just about any platform (taken from here):
def clearscreen(numlines=100):
"""Clear the console.
numlines is an optional argument used only as a fall-back.
"""
import os
if os.name == "posix":
# Unix/Linux/MacOS/BSD/etc
os.system('clear')
elif os.name in ("nt", "dos", "ce"):
# DOS/Windows
os.system('CLS')
else:
# Fallback for other operating systems.
print '\n' * numlines
word = raw_input("Your word: ")
import sys
sys.stdout.write("\x1b[1A" + 25*" " + "\n")
This will replace the last line printed with 25 spaces.
I think part of your problem is that input is echoing the Enter that terminates your word entry. Your backspaces are on another line, and I don't think they'll back up to the previous line. I seem to recall a SO question about how to prevent that, but I can't find it just now.
Also, I believe print, by default, will output a newline on each call, so each backspace would be on its own line. You can change this by using an end='' argument.
Edit: I found the question I was thinking of, but it doesn't look like there's any help there. You can look at it if you like: Python input that ends without showing a newline