I am trying to import a text file and encrypt/decrypt by two key words. I set a key variable but can't find the correct place to locate it.
Here is where it currently is:
def importFile():
importText = []
file = input('What is the text file name: ')
fileName = open(file,'r')
text = fileName.read()
fileName.close()
fileName = text
message = text
#print (text)
delete = open(file,'w')
delete.write('')
key = input ('What key do you wnat to use: ')
Here is where the key is called:
def translatedMessage(mode):
translated = []
keyIndex = 0
key = key.upper()
for symbol in message:
num =LETTERS .find(symbol.upper())
if num != -1:
if mode == 'encrypt':
num += LETTERS .find(key[keyIndex])
elif mode == 'decrypt':
num -= LETTERS .find(key[keyIndex])
num %= len(LETTERS)
if symbol.isupper():
translated.append(LETTERS[num])
elif symbol.islower():
translated.append(LETTERS[num].lower())
keyIndex += 1
if keyIndex == len(key):
keyIndex = 0
else:
translated.append(symbol)
return ''.join(translated)
if __name__ == '__main__':
main()
If you need it here is it all together:
LETTERS = 'ZABCDEFGHIJKLMNOPQRSTUVWXY'
def main():
myMode = input("Encrypt 'e' or Decrypt 'd': ")
if myMode == 'encrypt' or myMode == 'e':
translated = encryptFile()
elif myMode == 'decrypt' or myMode == 'd':
translated = decryptFile()
def importFile():
importText = []
file = input('What is the text file name: ')
fileName = open(file,'r')
text = fileName.read()
fileName.close()
fileName = text
message = text
#print (text)
delete = open(file,'w')
delete.write('')
key = input ('What key do you wnat to use: ')
def encryptFile():
textFile = input("Would you like to import a text file 'Y' or 'N': ")
if textFile.lower() == 'y' :
importFile()
return translatedMessage('encrypt')
def decryptFile():
textFile = input("Would you like to import a text file 'Y' or 'N': ")
if textFile.lower() == 'y' :
importFile()
return translatedMessage('decrypt')
def translatedMessage(mode):
translated = []
keyIndex = 0
key = key.upper()
for symbol in message:
num =LETTERS .find(symbol.upper())
if num != -1:
if mode == 'encrypt':
num += LETTERS .find(key[keyIndex])
elif mode == 'decrypt':
num -= LETTERS .find(key[keyIndex])
num %= len(LETTERS)
if symbol.isupper():
translated.append(LETTERS[num])
elif symbol.islower():
translated.append(LETTERS[num].lower())
keyIndex += 1
if keyIndex == len(key):
keyIndex = 0
else:
translated.append(symbol)
return ''.join(translated)
if __name__ == '__main__':
main()
I'm pretty new to coding and know this is pretty simple so any advice is greatly appreciated:)
The problem in your code is that you are treating key like a global variable, but it is a local one, so you need to pass it between your functions:
LETTERS = 'ZABCDEFGHIJKLMNOPQRSTUVWXY'
def main():
myMode = input("Encrypt 'e' or Decrypt 'd': ")
if myMode == 'encrypt' or myMode == 'e':
translated = encryptFile()
elif myMode == 'decrypt' or myMode == 'd':
translated = decryptFile()
def importFile():
importText = []
file = input('What is the text file name: ')
fileName = open(file,'r')
text = fileName.read()
fileName.close()
fileName = text
message = text
#print (text)
delete = open(file,'w')
delete.write('')
return input ('What key do you wnat to use: ') # Return the key
def encryptFile():
textFile = input("Would you like to import a text file 'Y' or 'N': ")
if textFile.lower() == 'y' :
key = importFile() # Get the key returned by the function
return translatedMessage('encrypt', key) # Pass the key to the function
def decryptFile():
textFile = input("Would you like to import a text file 'Y' or 'N': ")
if textFile.lower() == 'y' :
key = importFile() # Get the key returned by the function
return translatedMessage('decrypt', key) # Pass the key to the function
def translatedMessage(mode, key): # `key` is an argument
translated = []
keyIndex = 0
key = key.upper()
for symbol in message:
num =LETTERS .find(symbol.upper())
if num != -1:
if mode == 'encrypt':
num += LETTERS .find(key[keyIndex])
elif mode == 'decrypt':
num -= LETTERS .find(key[keyIndex])
num %= len(LETTERS)
if symbol.isupper():
translated.append(LETTERS[num])
elif symbol.islower():
translated.append(LETTERS[num].lower())
keyIndex += 1
if keyIndex == len(key):
keyIndex = 0
else:
translated.append(symbol)
return ''.join(translated)
if __name__ == '__main__':
main()
A simpler solution would be to define key as a global variable by adding the line global key to the importFile() function. In general however, I think using the global keyword in Python is discouraged.
This explanation of global vs. local variables in Python might be helpful: http://www.python-course.eu/global_vs_local_variables.php
Related
I'm getting the IndexError on line 50 (the sixth line of checkForDisallowedCharacters while j < len(resultSet[i]):)
I get this error when I input '***er', 't', and 'canpilru' into the console when prompted
Using my print statements I've found that this error occurs when the resultSet array has a length of 141, and when i is 0
resultSet[0] is 'paper' and it clearly exists
If anyone can explain why this is throwing an error I would be very grateful
import csv
import os
import sys
def buildDictionary():
dictionary = []
with open("./wordle-helper/wordle-dictionary.csv", newline='') as csvfile:
spamreader = csv.reader(csvfile, delimiter='\t')
for row in spamreader:
dictionary.append(row)
for i in range(len(dictionary)):
dictionary[i] = dictionary[i][0].lower()
return dictionary
def buildTestWordComposition(testWord):
testWordComposition = []
for i in range(len(testWord)):
if testWord[i] == "*":
testWordComposition.append(i)
return testWordComposition
def buildThreshold(testWord):
threshold = 0
for character in testWord:
if character != "*":
threshold += 1
return threshold
def checkForSoftMatches(dictionary, testWord, threshold):
resultSet = []
for word in dictionary:
testThreshold = 0
for i in range(5):
if testWord[i] == "*":
continue
elif testWord[i] == word[i]:
testThreshold += 1
if testThreshold == threshold:
resultSet.append(word)
return resultSet
def checkForDisallowedCharacters(resultSet, disallowedCharacters):
i = 0
while i < len(resultSet):
print(len(resultSet), i, resultSet[i][0])
j = 0
while j < len(resultSet[i]):
for character in disallowedCharacters:
if resultSet[i][j] == character:
try:
resultSet.remove(resultSet[i])
finally:
i -= 1
j = -1
break
j += 1
i += 1
if i < 0:
i = 0
elif i >= len(resultSet):
break
return resultSet
def checkForRequiredCharacters(resultSetNoDisallowedCharacters, requiredCharacters, testWordComposition):
resultSetChecked = []
threshold = len(requiredCharacters)
m = 0
resultSetCheckedLength = 0
while m < len(resultSetNoDisallowedCharacters):
compareToThreshold = 0
for aCharacter in requiredCharacters:
for number in testWordComposition:
if resultSetNoDisallowedCharacters[m][number] == aCharacter:
compareToThreshold += 1
break
if len(resultSetChecked) != resultSetCheckedLength:
break
if compareToThreshold == threshold:
resultSetChecked.append(resultSetNoDisallowedCharacters[m])
resultSetCheckedLength = len(resultSetChecked)
m += 1
return resultSetChecked
def wordleHelper(testWord, requiredCharacters=[], disallowedCharacters=[]):
dictionary = buildDictionary()
testWordComposition = buildTestWordComposition(testWord)
threshold = buildThreshold(testWord)
resultSet = checkForSoftMatches(dictionary, testWord, threshold)
resultSetNoDisallowedCharacters = checkForDisallowedCharacters(resultSet, disallowedCharacters)
resultSetChecked = checkForRequiredCharacters(resultSetNoDisallowedCharacters, requiredCharacters, testWordComposition)
if not resultSetChecked:
return resultSetNoDisallowedCharacters
return resultSetChecked
def printWordleHelper(testWord, requiredCharacters=[], disallowedCharacters=[]):
print("All possible words are listed below\n\n-----------------------------------------------\n")
for word in wordleHelper(testWord, requiredCharacters, disallowedCharacters):
print(word)
def handlePersistentCharacters(disallowedCharactersComplete):
willDisallowedCharactersPersist = input("Would you like to continue using your previous list of grey letters? (y/n): ")
if willDisallowedCharactersPersist == "y":
return disallowedCharactersComplete
elif willDisallowedCharactersPersist == "n":
return []
else:
print("Please enter a valid character")
handlePersistentCharacters(disallowedCharactersComplete)
def clearConsole():
if sys.platform.startswith('linux') or sys.platform.startswith('darwin'):
os.system('clear')
elif sys.platform.startswith('win'):
os.system('cls')
def buildParsed(unparsed):
parsed = []
for letter in unparsed:
parsed.append(letter)
return parsed
def handleUserContinue(disallowedCharactersComplete):
willUserContinue = input("Would you like to use World Helper (tm) again? (y/n): ")
if willUserContinue == "n":
sys.exit()
persistentDisallowedCharacters = handlePersistentCharacters(disallowedCharactersComplete)
if willUserContinue == "y":
promptUser(persistentDisallowedCharacters)
def promptUser(persistentDisallowedCharacters=[]):
clearConsole()
testWord = input("Please enter your Wordle guess in the form of *la*t where 'l', 'a', and 't' are the green letters from your guess, and the '*'s are yellow or grey letters from your guess: ")
requiredCharacters = input("Please enter your letters in yellow here in the form of 'abcxyz' (do not enter letters which are already in your Wordle guess string): ")
disallowedCharacters = input("Please enter your letters in grey here (in the form of 'abcxyz'): ")
requiredCharactersParsed = buildParsed(requiredCharacters)
disallowedCharactersParsed = buildParsed(disallowedCharacters)
disallowedCharactersComplete = persistentDisallowedCharacters + disallowedCharactersParsed
printWordleHelper(testWord, requiredCharactersParsed, disallowedCharactersComplete)
handleUserContinue(disallowedCharactersComplete)
promptUser()
So, I had 2 scripts, a Vigenere cipher and a Caesar cipher, however, when I decided to merge them into a "mainproject" file by using "import" to import the script after the wanted answer from the user is sent on the Terminal page, when I've done the code and decided to execute the mainproject, I've got the question whether to choose to use Vigenere or Caesar, once I typed caesar (1) it played the first 2-4 lines and stopped the code once I've encountered the "def" line on both of scripts, if thats the problem, I can't use imports with "def", how can I merge them both into one file that asks which script I would like to use?
Caesar:
import time
import sys
print("Welcome to Caesar Cipher")
time.sleep(3)
print("Choose the corresponding number to Encrypt or Decrypt in Caesar Cipher")
def encryption():
print("Encryption")
print("You have chose ENCRYPTION")
msg = input("Enter message: ")
key = int(input("Enter key(0-25): "))
encrypted_text = ""
for i in range(len(msg)):
if ord(msg[i]) == 32:
encrypted_text += chr(ord(msg[i]))
elif ord(msg[i]) + key > 122:
temp = (ord(msg[i]) + key) - 122
encrypted_text += chr(96+temp)
elif (ord(msg[i]) + key > 90) and (ord(msg[i]) <= 96):
temp = (ord(msg[i]) + key) - 90
encrypted_text += chr(64+temp)
else:
encrypted_text += chr(ord(msg[i]) + key)
print("Your Encrypted Message: " + encrypted_text)
def decryption():
print("Decryption")
print("You have chose DECRYPTION")
encrp_msg = input("Enter encrypted Text: ")
decrp_key = int(input("Enter key(0-25): "))
decrypted_text = ""
for i in range(len(encrp_msg)):
if ord(encrp_msg[i]) == 32:
decrypted_text += chr(ord(encrp_msg[i]))
elif ((ord(encrp_msg[i]) - decrp_key) < 97) and ((ord(encrp_msg[i]) - decrp_key) > 90):
temp = (ord(encrp_msg[i]) - decrp_key) + 26
decrypted_text += chr(temp)
elif (ord(encrp_msg[i]) - decrp_key) < 65:
temp = (ord(encrp_msg[i]) - decrp_key) + 26
decrypted_text += chr(temp)
else:
decrypted_text += chr(ord(encrp_msg[i]) - decrp_key)
print("Text has been Decrypted: " + decrypted_text)
choice = int(input("1. Encryption\n2. Decryption\nChoose(1,2): "))
if choice == 1:
encryption()
elif choice == 2:
decryption()
else:
print("Wrong Choice")
Vigenere:
import time
print("Welcome to Vigenere Cipher")
time.sleep(2)
print("Choose the corresponding number to Encrypt or Decrypt in Vigenere Cipher")
time.sleep(2.5)
def msg_and_key():
msg = input("Enter message: ").upper()
key = input("Enter key: ").upper()
key_map = ""
j=0
for i in range(len(msg)):
if ord(msg[i]) == 32:
key_map += " "
else:
if j < len(key):
key_map += key[j]
j += 1
else:
j = 0
key_map += key[j]
j += 1
return msg, key_map
def create_vigenere_table():
table = []
for i in range(26):
table.append([])
for row in range(26):
for column in range(26):
if (row + 65) + column > 90:
table[row].append(chr((row+65) + column - 26))
else:
table[row].append(chr((row+65)+column))
return table
def cipher_encryption(message, mapped_key):
table = create_vigenere_table()
encrypted_text = ""
for i in range(len(message)):
if message[i] == chr(32):
encrypted_text += " "
else:
row = ord(message[i])-65
column = ord(mapped_key[i]) - 65
encrypted_text += table[row][column]
print("Encrypted Message: {}".format(encrypted_text))
def itr_count(mapped_key, message):
counter = 0
result = ""
for i in range(26):
if mapped_key + i > 90:
result += chr(mapped_key+(i-26))
else:
result += chr(mapped_key+i)
for i in range(len(result)):
if result[i] == chr(message):
break
else:
counter += 1
return counter
def cipher_decryption(message, mapped_key):
table = create_vigenere_table()
decrypted_text = ""
for i in range(len(message)):
if message[i] == chr(32):
decrypted_text += " "
else:
decrypted_text += chr(65 + itr_count(ord(mapped_key[i]), ord(message[i])))
print("Decrypted Message: {}".format(decrypted_text))
print("Key and Message can only be alphabetic")
time.sleep(1.5)
choice = int(input("1. Encryption\n2. Decryption\nChoose(1,2): "))
if choice == 1:
print("You have chose ENCRYPTION")
message, mapped_key = msg_and_key()
cipher_encryption(message, mapped_key)
elif choice == 2:
print("You have chose DECRYPTION")
message, mapped_key = msg_and_key()
cipher_decryption(message, mapped_key)
else:
print("Wrong choice")
Any help would be appreciated!
def only defines a function. To actually execute it you need to call it.
It seems the following part should be outside of decryption function body i.e. indented to the left. It:
call be executed directly on the module level
can be a separate function e.g. main that you can call
As main:
def main():
choice = int(input("1. Encryption\n2. Decryption\nChoose(1,2): "))
if choice == 1:
encryption()
elif choice == 2:
decryption()
else:
print("Wrong Choice")
And now you can call the main function:
main()
Welcome to Stackoverflow. This answer ended up more as general advice than a specific point solution to your problem, but I hope it's helpful.
One obvious remark is that it would be nice not to have to import the code for the cypher you don't intend to use.
Imports are executable statements, so this is quite practical.
Your code is far from optimally organised. Much of the code on the two files is the same or very similar. This is not unusual for new programmers, as it takes a while to learn how to break problems down and extract the common elements. The real problem is that while it defines lots of functions, none of them actually get called (unless there's more code you haven't included).
I would recommend that you modify your code so that there's a top-level program that collects the key and data and performs the required operations, along with your two
encryption/decryption modules. The encryption and decryption routines shouldn't do any input or output at all, just deal with the data.
Let's assume you have a variable mtype that holds the type of encryption you want to use. The top-level logic could look something like this:
if mtype == "caesar":
from caesar import encrypt, decrypt
elif mtype == "vigniere":
from vigniere import encrypt, decrypt
else:
sys.exit("Unrecognised message type")
If this code succeeds you would then have an encrypt and a decrypt function from the correct module. This means that they have to have the same interface, since your logic must now be written to accommodate either.
The remainder of your logic would look something like this (untested):
operation = input("E(ncrypt) or D(ecrypt)? ")
if operation.upper().startswith("E"):
function = encrypt
elif operation.upper().startswith("D"):
function = decrypt
else:
sys.exit("Unknown operation")
message = input(...)
key = input(...)
output = function(message, key)
This will hopefully make your code clearer by separating out the I/O responsibility
from the encryption and decryption tasks.
Can somebody help me write the auto_key cipher in python. I understand the logic but don't know how to start.I wrote the code but it didn't work this is my auto_key cipher code, when I run it gives me the new
key if key is less than message. and then stops there, it doesn't work.thank you!
enter code here
ALPHA = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def main():
message = input('enter message:\n')
key = input('enter your key:\n')
mode = input('encrypt or decrypt\n')
if len(key) < len(message):
key = key[0:] + message[:100]
#print(key)
if mode == 'encrypt':
cipher = encryptMessage(message, key)
elif mode == 'decrypt':
cipher = decryptMessage(message, key)
#print(' message:', (mode.title()))
print(cipher)
def encryptMessage (keys, messages):
return cipherMessage(keys, messages, 'encrypt')
def decryptMessage(keys,messages):
return cipherMessage(keys, messages, 'decrypt')
def cipherMessage (keys, messages, mode):
cipher = []
k_index = 0
key = keys.upper()
for i in messages:
text = ALPHA.find(i.upper())
if text != -1:
if mode == 'encrypt':
text += ALPHA.find(key[k_index])
elif mode == 'decrypt':
text -= ALPHA.find(key[k_index])
text %= len(ALPHA)
k_index += -1
if k_index == len(key):
k_index = 0
else:
cipher.append(i)
return ''.join(cipher)
if __name__ == "__main__":
main()
Even though I fixed your code I recommend you start all over again.
Your code is a mess! :D
It works now, but it will still fail if the input does not fit, the logic you implemented.
Let's go:
Lines 8-9:
Useless at this point!
Note: What would happen if len(key) == 5 and len(message) == 130?
Line 16-17, 18-19 and 20:
In line 10 and 13 you call function(message, key), but here you
call:
def function((keys, messages)):
return cipherMessage((keys, messages), 'encrypt')
You switched message and key, that was the reason for the IndexError.
Line 26:
Useless in this for-loop
Line 34:
k_index must be increased!
Line 35-37:
this if is useless in this for-loop
this else: is the reason cipher.append(i) is never reached
Line 38:
To cipher you need to add the shortly encrypted/decrypted char , not the
char form message
Fixing all that, you'll get the below code.
Note: comments with ## indicate what I commented out of your code.
ALPHA = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def main():
message = input('enter message:\n')
key = input('enter your key:\n')
mode = input('encrypt or decrypt\n')
## if len(key) < len(message):
## key = key[0:] + message[:100]
#print(key)
if mode == 'encrypt':
cipher = encryptMessage(message, key)
elif mode == 'decrypt':
cipher = decryptMessage(message, key)
#print(' message:', (mode.title()))
print(cipher)
## def encryptMessage (keys, messages):
## return cipherMessage(keys, messages, 'encrypt')
def encryptMessage (messages, keys):
return cipherMessage(messages, keys, 'encrypt')
## def decryptMessage(keys,messages):
## return cipherMessage(keys, messages, 'decrypt')
def decryptMessage(messages, keys):
return cipherMessage(messages, keys, 'decrypt')
## def cipherMessage (keys, messages, mode):
def cipherMessage (messages, keys, mode):
cipher = []
k_index = 0
key = keys.upper()
for i in messages:
text = ALPHA.find(i.upper())
## if text != -1:
if mode == 'encrypt':
text += ALPHA.find(key[k_index])
key += i.upper() # add current char to keystream
elif mode == 'decrypt':
text -= ALPHA.find(key[k_index])
key += ALPHA[text] # add current char to keystream
text %= len(ALPHA)
## k_index += -1
k_index += 1
## if k_index == len(key):
## k_index = 0
## else:
cipher.append(ALPHA[text])
return ''.join(cipher)
if __name__ == "__main__":
main()
For some reason I get an error in python 2.7 when running this and entering in my 26 letter key. It says that the list index is out of range. Any help would be greatly appreciated. Thanks! (And I know I could've used a loop for the encrypter)
#-------------------------#
# Code Translator #
#-------------------------#
message = ''
messagearray = []
user = ''
encrypted = []
decrypted = []
keystring = ''
alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
dataset = []
keyarray = []
def encrypter():
keystring = raw_input("Please paste key: ")
message = raw_input("Message to Encrypt: ")
for char in message:
if char == alphabet[0]:
messagearray.append(keyarray[0])
elif char == alphabet[1]:
messagearray.append(keyarray[1])
elif char == alphabet[2]:
messagearray.append(keyarray[2])
elif char == alphabet[3]:
messagearray.append(keyarray[3])
elif char == alphabet[4]:
messagearray.append(keyarray[4])
elif char == alphabet[5]:
messagearray.append(keyarray[5])
elif char == alphabet[6]:
messagearray.append(keyarray[6])
elif char == alphabet[7]:
messagearray.append(keyarray[7])
elif char == alphabet[8]:
messagearray.append(keyarray[8])
elif char == alphabet[9]:
messagearray.append(keyarray[9])
elif char == alphabet[10]:
messagearray.append(keyarray[10])
elif char == alphabet[11]:
messagearray.append(keyarray[11])
elif char == alphabet[12]:
messagearray.append(keyarray[12])
elif char == alphabet[13]:
messagearray.append(keyarray[13])
elif char == alphabet[14]:
messagearray.append(keyarray[14])
elif char == alphabet[15]:
messagearray.append(keyarray[15])
elif char == alphabet[16]:
messagearray.append(keyarray[16])
elif char == alphabet[17]:
messagearray.append(keyarray[17])
elif char == alphabet[18]:
messagearray.append(keyarray[18])
elif char == alphabet[19]:
messagearray.append(keyarray[19])
elif char == alphabet[20]:
messagearray.append(keyarray[20])
elif char == alphabet[21]:
messagearray.append(keyarray[21])
elif char == alphabet[22]:
messagearray.append(keyarray[22])
elif char == alphabet[23]:
messagearray.append(keyarray[23])
elif char == alphabet[24]:
messagearray.append(keyarray[24])
elif char == alphabet[25]:
messagearray.append(keyarray[25])
print ''.join(messagearray)
def decrypter():
keystring = raw_input("Please paste key: ")
message = raw_input("Message to Decrypt: ")
def outputM():
print decrypted
def userChoice():
user = raw_input("Encrypt or Decrypt?")
if user.upper() == "ENCRYPT":
encrypter()
elif user.upper() == "DECRYPT":
decrypter()
else:
print "Please enter a valid command."
userChoice()
for char in keystring:
keyarray.append(char)
userChoice()
Here's the full traceback I get:
Traceback (most recent call last):
File "translate.py", line 102, in <module>
userChoice()
File "translate.py", line 92, in userChoice
encrypter()
File "translate.py", line 43, in encrypter
messagearray.append(keyarray[11])
IndexError: list index out of range
The problem is here:
for char in keystring:
keyarray.append(char)
keystring is empty so also keyarray will remain empty. In order not to have IndexError you would need a keystring as much longer as the alphabet (since basically you are just substituting chars)
The problem is that in:
def decrypter():
keystring = raw_input("Please paste key: ")
message = raw_input("Message to Decrypt: ")
you are assigning the values to local variables, so the global ones remain empty. If you want to modify the global variables you have to state so:
def decrypter():
global keystring, message
keystring = raw_input("Please paste key: ")
message = raw_input("Message to Decrypt: ")
the same is true for encrypter.
Also, you cannot create keyarray before having taken some input!
There are also many other issues with the code. You cannot possibly think that doing all the manual indexing is the best way to proceed. What if you want to support a 128 character alphabet?
Use loops:
for char in message:
for i, c in enumerate(alphabet):
if char == c:
messagearray.append(keyarray[i])
(Instead of all those repeating lines).
Moreover strings already provide a method to do exactly what you are trying to do. It's called translate.
You could simply do:
import string
table = str.maketrans(string.ascii_lowercase, keystring)
And then use:
decrypted_text = some_encrypted_text.translate(table)
example run:
In [1]: import string
...: alphabet = string.ascii_lowercase
...: table = str.maketrans(alphabet, alphabet[3:]+alphabet[:3])
...:
In [2]: 'hello'.translate(table)
Out[2]: 'khoor'
The above is for python3+. In python2.7 you have to use string.maketrans instead of str.maketrans. So you'd have to do:
In [1]: import string
...: alphabet = string.ascii_lowercase
...: table = string.maketrans(alphabet, alphabet[3:]+alphabet[:3])
...:
In [2]: 'hello'.translate(table)
Out[2]: 'khoor'
import sys
import pickle
import string
def Menu():
print ("\n***********MENU************")
print ("0. Quit")
print ("1. Read text file")
print ("2. Display counts")
print ("3. Display statistics of word lengths")
print ("4. Print statistics to file")
def Loop():
choice = -1
while choice !=0:
Menu()
choice = (int(input("Please choose 1-4 to perform function. Press 0 to exit the program. Thank you. \n")))
if choice == 0:
print ("Exit program. Thank you.")
sys.exit
elif choice == 1:
user_File = ReadTextFile()
elif choice == 2:
DisplayCounts(user_File)
elif choice == 3:
DisplayStats(user_File)
elif choice == 4:
PrintStats(aDictionary)
else:
print ("Error.")
def ReadTextFile():
print "\n"
while True:
InputFile = input("Please enter a file name (NOTE: must have quotation marks around name and extension): ")
if (InputFile.lower().endswith('.txt')):
break
else:
print("That was an incorrect file name. Please try again.")
continue
return InputFile
def DisplayCounts(InputFile):
print "\n"
numCount = 0
dotCount = 0
commaCount = 0
lineCount = 0
wordCount = 0
with open(InputFile, 'r') as f:
for line in f:
wordCount+=len(line.split())
lineCount+=1
for char in line:
if char.isdigit() == True:
numCount+=1
elif char == '.':
dotCount+=1
elif char == ',':
commaCount+=1
print("Number count: " + str(numCount))
print("Comma count: " + str(commaCount))
print("Dot count: " + str(dotCount))
print("Line count: " + str(lineCount))
print("Word count: " + str(wordCount))
def DisplayStats(InputFile):
print "\n"
temp1 = []
temp2 = []
lengths = []
myWords = []
keys = []
values = []
count = 0
with open(InputFile, 'r') as f:
for line in f:
words = line.split()
for word in words:
temp2.append(word)
temp1.append(len(word))
for x in temp1:
if x not in lengths:
lengths.append(x)
lengths.sort()
dictionaryStats = {}
for x in lengths:
dictionaryStats[x] = []
for x in lengths:
for word in temp2:
if len(word) == x:
dictionaryStats[x].append(word)
for key in dictionaryStats:
print("Key = " + str(key) + " Total number of words with " + str(key) + " characters = " + str(len(dictionaryStats[key])))
return dictionaryStats
def PrintStats(aDictionary):
print "\n"
aFile = open("statsWords.dat", 'w')
for key in aDictionary:
aFile.write(str(key) + " : " + str(aDictionary[key]) + "\n")
aFile.close()
Loop()
There's something with that last function that is really tripping me up. I keep getting errors. I know aDictionary is not defined but I do not even know what to define it as! Any of you guys have an idea? Thanks.
with open("some_file.txt","W") as f:
print >> f, "Something goes here!"
its hard to say without your errors. .. but you almost certainly need to have aDictionary defined
also probably something like
def DisplayCounts(InputFile):
print "\n"
numCount = 0
dotCount = 0
commaCount = 0
lineCount = 0
wordCount = 0
with open(InputFile, 'r') as f:
for line in f:
wordCount+=len(line.split())
lineCount+=1
for char in line:
if char.isdigit() == True:
numCount+=1
elif char == '.':
dotCount+=1
elif char == ',':
commaCount+=1
return dict(numbers=numCount,
comma=commaCount,
dot=dotCount,
line=lineCount,
word=wordCount)
result = DisplayCounts("someinput.txt")
print result