I am trying to encrypt a file input by user into a randomized key of ascii. I got the random key and can translate the string in the file into ascii but cannot figure out how to translate it into the key
I tried many things but am not good enough in python to understand what else to try/ what I could be doing wrong
import random
lst = list(range(1,128)) #for key
numbersran = list()
while len(numbersran) < 128:
candidate = random.randint(1,128)
if candidate not in numbersran:
numbersran.append(candidate)
listsdict = dict(zip(lst,numbersran)) #makes the key
print("Encytption key=", listsdict)
print()
filename=input("Enter File: ")
file=open(filename, "r")
filetxt=file.readlines()
file.close() #for user input file
with open('file name here','r') as f: #also cant figure out how to make this work with user inputted file
for x in f:
arr=list(x)
ctd=list(map(str,map(ord,arr)))
filename=filename.replace('.txt','')
encrypt=open(filename,"w")
#below is for the encryption process
import random
lst = list(range(1,128)) #for key
# numbersran = list()
# while len(numbersran) < 128:
# candidate = random.randint(1,128)
# if candidate not in numbersran:
# numbersran.append(candidate)
random.shuffle(lst)
listsdict = dict(zip(lst, range(1,128))) #makes the key
print("Encytption key=", listsdict)
print()
filename=input("Enter File: ")
# file=open(filename, "r")
# filetxt=file.readlines()
# file.close()
with open(filename, "r") as file:
filetxt = file.read()
ascii_codes = [ord(c) for c in filetxt]
# with open('file name here','r') as f: #also cant figure out how to make this work with user inputted file
# for x in f:
# arr=list(x)
# ctd=list(map(str,map(ord,arr)))
# listdict is the key!
encrypted_codes = [listsdict[code] for code in ascii_codes]
print(encrypted_codes)
cypher = "".join([chr(c) for c in encrypted_codes])
print(cypher)
# filename=filename.replace('.txt','')
# encrypt=open(filename,"w")
#below is for the encryption process
Related
I encrypted a file from ascii randomized key. I need to decrypt back into normal letters from and then put that into a new file
import random
lst = list(range(1,128)) #for key
numbersran = list()
while len(numbersran) < 128:
candidate = random.randint(1,128)
if candidate not in numbersran:
numbersran.append(candidate)
listsdict = dict(zip(lst,numbersran)) #makes key, changes every time
print("Encytption key=", listsdict)
print()
filename=input("Enter File: ")
with open(filename, "r") as file:
filetxt = file.read()
ascii_codes = [ord(c) for c in filetxt]
encrypted_codes = [listsdict[code] for code in ascii_codes]
print('\nEncrypted file: ',encrypted_codes)
cypher = "".join([chr(c) for c in encrypted_codes]) #encrypts from key
#decrypt below here into a file using the key to translate (should be original text from file)
I am not too sure how to reverse the process back to the original text in file. Must be decrypted back, can't just be copied from og file
The decryption process should be reverse of what has been done for encryption. Find below the code snippet.
decrypted_file = [ord(c) for c in cypher]
decrypted_key = list()
for value in decrypted_file:
for key in listsdict:
if listsdict[key] == value:
decrypted_key.append(key)
break
print(''.join([chr(c) for c in decrypted_key]))
There can be better ways to achieve the decryption but the solution in its naivest form should be like above.
easy way to replace this code snippet:
for value in decrypted_file:
for key in listsdict:
if listsdict[key] == value:
decrypted_key.append(key)
break
is to reverse listsdict keys with value as suggested by #scott hunter
decrypted_file = [ord(c) for c in cypher]
decrypted_key = list()
listsdict = dict(zip(numbersran,lst))
decrypted_key = [listsdict[code] for code in decrypted_file]
print(''.join([chr(c) for c in decrypted_key]))
if the file for example contains:
A: GHJIG
B: AHYFASF
C: IYDDFG
f = open(example.txt)
I want to store the file contents in a table and then the program should ask the user to enter a character and print the line without the alphabet.
input: A
output: GHJIG
how to do it?
Try this:
with open('test.txt','r') as file:
content = file.readlines()
my_dict = {}
for line in content:
split = line.split(':')
my_dict[split[0]] = split[1]
input = raw_input("Choose a letter")
if input in my_dict:
print my_dict[input]
It would be better to use a OrderedDict from collections, because default dictionary has a not a precise order.
Try the solution below, you can provide a useful message if the user enters any alphabet which is not present in your txt file.
with open('/home/pydev/Desktop/t1.txt', 'r') as file_obj:
content = file_obj.readlines()
sample_dict = {}
for value in content:
sample_dict[value.split(':')[0]] = value.split(':')[1]
input_key = raw_input("Please enter an alphabet: \n")
print sample_dict.get(input_key, "No value exists")
def false_to_true():
name = input("Input name: ")
file=open("users.txt","r")
lines = file.readlines()
file.close()
for line in lines:
username, lel, type = line.split("/")
while name == username:
name = input("input name again: ")
tip = True
with open("users.txt", "w") as users:
users.write(str(red))
#
#I do not know how to perform a given modification and enrollment into place in #the text.
#
#I wont to change word False to True for username i input.
#I have this text in file users:
#Marko123/male/False
#Mimi007/female/False
#John33/male/False
#Lisa12/female/False
#Inna23/female/False
#Alisa27/female/False
I won't to change word False to True for username I input.
I have this text in file users:
Marko123/male/False
Mimi007/female/False
John33/male/False
Lisa12/female/False
Inna23/female/False
Alisa27/female/False
You can just use the csv library and forget about string manipulation:
import csv
def false_to_true():
#read from user.txt file into list(data)
with open('users.txt', 'r') as userfile:
data = [row for row in csv.reader(userfile,
delimiter="/",
quoting=csv.QUOTE_NONE)]
while True:
#waiting for input until you enter nothing and hit return
username = input("input name: ")
if len(username) == 0:
break
#look for match in the data list
for row in data:
if username in row:
#change false to true
row[2] = True
#assuming each username is uniqe break out this for loop
break
#write all the changes back to user.txt
with open('users.txt', 'w', newline='\n') as userfile:
dataWriter = csv.writer(userfile,
delimiter="/",
quoting=csv.QUOTE_NONE)
for row in data:
dataWriter.writerow(row)
if __name__ == '__main__':
false_to_true()
Open the input and output files, make a set out of the user-input names (terminated by a blank line), then create a generator for strings of the proper format that check for membership in the user-input names, then write these lines to the output file:
with open('names.txt') as f, open('result.txt', 'w') as out:
names = {name for name in iter(input, '')}
f = ('{}/{}/{}'.format(a,b,'True\n' if a in names else c) for a,b,c in (line.split('/') for line in f))
output.writelines(f)
To modify a text file inplace, you could use fileinput module:
#!/usr/bin/env python3
import fileinput
username = input('Enter username: ').strip()
with fileinput.FileInput("users.txt", inplace=True, backup='.bak') as file:
for line in file:
if line.startswith(username + "/"):
line = line.replace("/False", "/True")
print(line, end='')
See How to search and replace text in a file using Python?
Ask for name and iterate throw your lines to check for username, like this:
def false_to_true():
name = input("Input name: ")
file=open("users.txt","r")
lines = file.readlines()
file.close()
users = open("users.txt", "w")
for line in lines:
username, lel, type = line.split("/")
if name == username:
type = 'True\n'# \n for new line type ends with '\n'
users.write("/".join([username, lel, type]))
users.close()
false_to_true()
How can I intersect a dictionary key (that is a text file) and print the value from the key that generated the longest list? This is what I got so far. My question is at the end of the code.
#define intersection between user text input and my file inputs
def me_and_the_plant(m, p):
return list(set(m) & set(p))
#get user text input
words = raw_input("Say anything that comes to your mind: ")
print
input_words = words.split()
#define valid user input
if len(input_words) < 3:
print "I need more than that."
Mithras()
else:
me = input_words
#make dictionary with my input files
songs = {"Wicked.txt" : "Wicked.wav",
"Requiem.txt" : "Requiem.wav"}
#use text files as keys
for lyrics in songs.keys():
f = open(lyrics)
r = f.read()
the_plant = r.split()
#for the key that gets the most intersections, print its value
print me_and_the_plant(me, the_plant)
Change the loop at the end to figure out which one has the most:
...
#use text files as keys
most_intersection_key = None
most_intersection = None
most_intersection_len = 0
me = me.split()
for lyrics in songs:
with open(lyrics) as f:
the_plant = f.read().split()
intersection = me_and_the_plant(me, the_plant)
intersection_len = len(intersection)
if intersection_len > most_intersection_len: # most seen?
most_intersection_key = lyrics
most_intersection_len = intersection_len
most_intersection = intersection
if most_intersection_key:
print most_intersection_key, most_intersection_len, most_intersection
else:
print 'there were no intersections'
You could simplify it slightly using thecollections.Counterclass and getting rid of the one lineme_and_the_plant()function:
...
from collections import Counter
intersection_lengths = Counter()
intersections = {}
me = me.split()
for song_filename in songs:
with open(song_filename) as f:
lyrics = f.read().split()
intersections[song_filename] = set(me) & set(lyrics)
intersection_lengths[song_filename] = len(intersections[song_filename])
most_intersections = intersection_lengths.most_common(1)
if most_intersections:
print most_intersections[0], most_intersections[1], \
list(intersections[most_intersections[0]])
else:
print 'there were no intersections'
I am able to open the rules file and create a dictionary to use for my encryption. I have to also create a dictionary to use for decrypting text. I assume it's basically the same function with minor changes. The encrypt works fine, but I can't get the decrypt to work. My second problem is that while I encrypted the file I took out all spaces and punctuation. I can't figure out how to get those back in the output file once I run the program. It just prints in a single column. Lastly I have to output this to a .txt file. I am able to create a .txt with a user assigned name, but can't get anything to print on the file.
Here is what I achieved so far.
#import clauses
import string
#function definitions
#encrypt dictionary
def createrulesdictencrypt(openFile):
rulesencrypt1 = {}
for line in openFile:
rulessplit = string.split(string.strip(line))
rulesencrypt1[rulessplit[0]] = rulessplit[1]
return rulesencrypt1
#decrypt dictionary
def createrulesdictdecrypt(openFile):
rulesdecrypt1 = {}
for line in openFile:
rulessplit = string.split(string.strip(line))
rulesdecrypt1[rulessplit[1]] = rulessplit[0]
return rulesdecrypt1
openFile = open('rules.txt', 'r')
rulesencrypt = createrulesdictencrypt(openFile)
rulesdecrypt = createrulesdictdecrypt(openFile)
#print rulesencrypt
#print rulesdecrypt
#function for encrypting file
def encryptfile(openFile2):
for line in openFile2:
for word in line.split():
empty = ''
for char in word:
if char not in string.punctuation:
char=char.lower()
empty = empty+char
if len(empty) == 2:
print rulesencrypt[empty]
empty = ''
if len(empty) == 1:
print rulesencrypt[empty]
#function for decrypting file
def decryptfile(openFile2):
for line in openFile2:
for word in line.split():
empty = ''
for char in word:
if char not in string.punctuation:
char=char.lower()
empty = empty+char
if len(empty) == 2:
print rulesdecrypt[empty]
empty = ''
if len(empty) == 1:
print rulesdecrypt[empty]
#main program
ende = raw_input("To encrypt a file, enter '0':\nTo decrypt a file, enter '1':")
filename = raw_input("Enter the name of the file to be processed:")
outfilename = raw_input("Enter the name of the file to save the result to:")
openFile2 = open(filename, 'r')
outputfile = open(outfilename, 'w')
fileencrypt = encryptfile(openFile2)
filedecrypt = decryptfile(openFile2)
if ende == "0":
print encryptfile(fileencrypt)
if ende == "1":
print decryptfile(filedecrypt)
This is what I am trying to encrypt
Sir Robin: "Oh, you liars!"
Minstrel: [singing] "Bravely taking to his feet, he beat a very brave
retreat. A brave retreat by brave Sir Robin."
Your first problem is that you're not actually writing your encrypted text to a file, instead you're just printing it to sys.stdout. Incidentally, print appends a \n to it's output by default.
You could rewrite your decrypt function as follows:
#function for decrypting file
def decryptfile(openFile2, outfile): # <- CHANGED to add outfile
for line in openFile2:
for word in line.split():
empty = ''
for char in word:
if char not in string.punctuation:
char=char.lower()
empty = empty+char
if len(empty) == 2:
outfile.write(rulesdecrypt[empty]) # <- CHANGED to write to file
empty = ''
if len(empty) == 1:
outfile.write(rulesdecrypt[empty]) # <- CHANGED to write to file
You will then need to invoke the decryptfile function with a file as its second argument. A similar change could be made to the encryptfile function.
With respect to punctuation and whitespace, either encrypt it or just leave it in place. Once you've removed it, there really isn't a good way to replace it.