create a table using file contents python - python

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")

Related

Encrypting a file into ascii key

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

Python replace word for line [duplicate]

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()

Array/List from txt file in Python

I was trying to get value from .txt file into array/list in python.
Let's say I have this data in user.txt :
ghost:001
ghost:002
ghost:003
So, when I want to output it as :
'ghost:001','ghost:002','ghost:003'
I use this function
def readFromFile(filename, use_csv):
userlist = ''
userlist_b = ''
print ("Fetching users from '%s'"% filename)
f = open (filename,"r")
for line in f:
userlist+=str(line)
userlist = "','".join(userlist.split("\n"))
userlist = "'" + userlist + "'"
userlist = "(%s)" %userlist
return userlist
My question is how could I do this:
I want to print specific user. Something like
idx = 2
print("User[%s] : %s",%idx, %(array[idx]))
*output:*
User[2] : ghost:003
How do I form the array?
Could anyone help me?
I would store the users in a dict where the keys increment for each user:
d = {}
with open("in.txt") as f:
user = 1
for line in f:
d[user]= line.rstrip()
user += 1
print(d)
{1: 'ghost:001', 2: 'ghost:002', 3: 'ghost:003'}
If you just want a list of user and to access by index:
with open("in.txt") as f:
users = f.readlines()
print("User {}".format(users[0]))
User ghost:001
Look into loading dictionaries. This code should help you.
import json
import pickle
d = { 'field1': 'value1', 'field2': 2, }
json.dump(d,open("testjson.txt","w"))
print json.load(open("testjson.txt","r"))
pickle.dump(d,open("testpickle.txt","w"))
print pickle.load(open("testpickle.txt","r"))
If you want the file (one big string) split out into smaller strings, don't build up a new string, then split it apart again. Just append each line to a list:
def readFromFile(filename, use_csv):
userlist = []
print ("Fetching users from '%s'"% filename)
with open(filename,"r") as f:
for line in f.read():
userlist.append(line)
return userlist
array = readFromFile('somefile', use_csv)
idx = 2
print("User[%s] : %s" % (idx, array[idx]))
Not sure about the User['idx'] part of you desire.
Try to use list comprehensions.
Use indexing rather than dictionaries if that's all you need. (I can add a dict version if the seconds part of the line is really the index you are looking up)
# read the file and use strip to remove trailing \n
User = [line.strip() for line in open(filename).readlines()]
# your output
print "User[2] : %s"%User[2]
# commented line is more clear
#print ','.join(User)
# but this use of repr adds the single quotes you showed
print ','.join(repr(user) for user in User)
output:
User[2] : ghost:003
'ghost:001','ghost:002','ghost:003'

Parsing Input File in Python

I have a plain text file with some data in it, that I'm trying to open and read using a Python (ver 3.2) program, and trying to load that data into a data structure within the program.
Here's what my text file looks like (file is called "data.txt")
NAME: Joe Smith
CLASS: Fighter
STR: 14
DEX: 7
Here's what my program looks like:
player_name = None
player_class = None
player_STR = None
player_DEX = None
f = open("data.txt")
data = f.readlines()
for d in data:
# parse input, assign values to variables
print(d)
f.close()
My question is, how do I assign the values to the variables (something like setting player_STR = 14 within the program)?
player = {}
f = open("data.txt")
data = f.readlines()
for line in data:
# parse input, assign values to variables
key, value = line.split(":")
player[key.strip()] = value.strip()
f.close()
now the name of your player will be player['name'], and the same goes for all other properties in your file.
import re
pattern = re.compile(r'([\w]+): ([\w\s]+)')
f = open("data.txt")
v = dict(pattern.findall(f.read()))
player_name = v.get("name")
plater_class = v.get('class')
# ...
f.close()
The most direct way to do it is to assign the variables one at a time:
f = open("data.txt")
for line in f: # loop over the file directly
line = line.rstrip() # remove the trailing newline
if line.startswith('NAME: '):
player_name = line[6:]
elif line.startswith('CLASS: '):
player_class = line[7:]
elif line.startswith('STR: '):
player_strength = int(line[5:])
elif line.startswith('DEX: '):
player_dexterity = int(line[5:])
else:
raise ValueError('Unknown attribute: %r' % line)
f.close()
That said, most Python programmers would stored the values in a dictionary rather than in variables. The fields can be stripped (removing the line endings) and split with: characteristic, value = data.rstrip().split(':'). If the value should be a number instead of a string, convert it with float() or int().

Use substitution cipher in python to encrypt and decrypt a .txt file and output to a new .txt file

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.

Categories