search for string in json file - python

i have a dictionary which the user enters values in at the beginning, those values are then stored into a txt file in json format. The goal is for the user to be able to search the json file with a string of their choice. I have tried a variety of ways but have come up unsuccesful. The code below shows if the user enters 's' then they will be prompted to enter a search term. the code then loads the json file and stores the information from the file into a "list" called "data", then the code attempts to search every item within the list and compare it to the searchTerm inputted from the user
code that puts the users input into the txt file (json format)
if choice == 'a':
# Add a new joke.
# See Point 3 of the "Requirements of admin.py" section of the assignment brief.
jokeSetup = input('Enter setup of joke: ')
jokePunchLine = input('Enter puncline of joke: ')
entry = {'setup': jokeSetup , 'punchline': jokePunchLine}
data.append(entry)
file = open('data.txt', 'w')
json.dump(data, file)
file.close()
print('Joke Added.')
pass
elif choice == 's':
# Search the current jokes.
# See Point 5 of the "Requirements of admin.py" section of the assignment brief.
searchTerm = input('Enter search term: ')
file = open('data.txt', 'r')
data = json.load(file)
file.close()
for item in data:
if searchTerm in data:
print ('found it')
pass

import json
import sys
import os
data = []
if os.stat("data.txt").st_size != 0 :
file = open('data.txt', 'r')
data = json.load(file)
print(data)
choice = input("What's your choice ?")
if choice == 'a':
# Add a new joke.
# See Point 3 of the "Requirements of admin.py" section of the assignment brief.
jokeSetup = input('Enter setup of joke: ')
jokePunchLine = input('Enter punchline of joke: ')
entry = {'setup': jokeSetup , 'punchline': jokePunchLine}
data.append(entry)
file = open('data.txt', 'w')
json.dump(data, file)
file.close()
print('Joke Added.')
pass
elif choice == 's':
# Search the current jokes.
# See Point 5 of the "Requirements of admin.py" section of the assignment brief.
searchTerm = input('Enter search term: ')
file = open('data.txt', 'r')
data = json.load(file)
file.close()
for sub_dict in data:
if searchTerm in sub_dict['setup']:
print(sub_dict['punchline'])
pass
# or you could modify the last for loop, like this:
for dict in data:
if searchTerm in dict['setup'] or searchTerm in dict['punchline']:
print('found!')
pass

You could do it like this:
if choice == 'a':
# Add a new joke.
# See Point 3 of the "Requirements of admin.py" section of the assignment brief.
jokeSetup = input('Enter setup of joke: ')
jokePunchLine = input('Enter punchline of joke: ')
entry = {'setup': jokeSetup , 'punchline': jokePunchLine}
data.append(entry)
file = open('data.txt', 'w')
json.dump(data, file)
file.close()
print('Joke Added.')
pass
elif choice == 's':
# Search the current jokes.
# See Point 5 of the "Requirements of admin.py" section of the assignment brief.
searchTerm = input('Enter search term: ')
file = open('data.txt', 'r')
data = json.load(file)
file.close()
for item in data[0].items():
if searchTerm in str(item[1]):
print ('found it')
pass
# or the for loop could be like this
for sub_dict in data:
if searchTerm in sub_dict['setup'] or searchTerm in sub_dict['punchline']:
print('found!')

Related

Finding desired search result from list in Txt file with python

def add():
while True:
try:
a = int(input("How many words do you want to add:"))
if a >= 0:
break
else:
raise ValueError
except ValueError:
print("Not valid ")
return a
for i in range(add()):
key_i = input(f"Turkish meaning: {i + 1}: ")
value_i = input("translated version: ")
with open('words.txt', 'a+') as f:
f.write("'"+key_i+':')+ f.write(value_i+"'"+",")
My goal is to create my own dictionary,but I am adding a list into the txt file, so it is added into the txt file like this
words = {'araba:kol',
but when I search the txt file it gives me the whole list
def search():
while 1:
search = str(input("Search: "))
if search not in["exit", "Exit"]:
with open('words.txt', 'r+') as f:
line = f.readline()
while line:
data = line.find(search)
if not data == -1:
print(line.rstrip('\n'))
line = f.readline()
else:
line = f.readline()
else:
break
f.close()
What can I do to make it output like this
car:araba
Use JSON module to avoid having to write the dictionary line by line yourself.
import json
with open('words.json', 'a+') as f:
json.dump({key_i: value_i}, f)
with open('data.json', 'r') as f:
d2 = json.load(f)
d2 is now the data that you wrote to the file.
Note, that you should change the a+ to 'w' as you only have one dictionary per file.

Creating an object from a list of attributes in a file, Python

I have a file full of lines, where each line has attributes for a bank account object. Example of file layout:
1,IE33483,alex,1,100,20,s
2,IE30983,joe,1,0,20,c
3,IE67983,tom,1,70,20,s
Im trying to create some code that will search this file for user input (e.g they enter their id which is the first element of each line), and will use these all 3 attributes to create an object. Any help? This is what I have tried so far, but it doesn't seem to work for a file with more than one line:
accid=input("Enter ID of account to manage:\n")
f = open("accounts.txt", "r")
for line_str in f:
split_line = line_str.split(",")
accid2 = split_line[0].strip()
if split_line[6] == 's':
for line in split_line:
if accid2 == accid:
current_acc=SavingsAccount(accid, split_line[1],
split_line[2],
split_line[3],
split_line[4],
split_line[5],
split_line[6])
print("Logged in as: ")
print(current_acc.accid)```
You can do something like this - no need to iterate through the parts within each line.
def get_account_by_id(id, type_)
with open("accounts.txt") as f:
for line in f:
parts = line.split(",")
if parts[0] == id and parts[6] == type_:
return SavingsAccount(*parts)
accid = input("Enter ID of account to manage:\n")
account = get_account_by_id(accid, type_="s")
if account is not None:
print(f"Logged in as {account.accid}")
Or better, if your file is a valid CSV file, use the CSV module
import csv
def get_account_by_id(id, type_)
with open("accounts.txt") as f:
for row in csv.reader(f):
if row[0] == id and row[6] == type_:
return SavingsAccount(*row)

school assignment regarding inverting Dictionary with Tuple[Keys] and string[values], writing to text file

inverting Dictionary with Tuple[Keys] and string[values], writing dictionary to a text file, then reading the text file, and inverting the keys-values back to original order.
I'm just <json - .dumps/.loads> to convert the data to a string to save, and then back into a dictionary. The problem is that I'm getting an error code trying to invert the values and keys back... my error is
TypeError: string indices must be integers
Here is my code:
import json
def invert_roster(d):
inverse = dict()
for key in d:
val = d[key]
if val not in inverse:
inverse[val] = [key]
else:
inverse[val].append(key)
return inverse
a = 0
def choice(c):
a = ' '
choice = input('Enter <add> to add to file, or <view> to view file.')
if choice == 'add':
add(a)
elif choice == 'view':
view_file(a)
def add(a):
rf = 0
choice2 = input('<new> File or <old> File?')
if choice2 == 'new':
new_file()
elif choice2 =='old':
read_file(rf)
roster = dict()
name = ' '
print('Enter <stop> to exit.')
while name != 'stop':
name = input('Enter first and last name of patient: ')
if name == 'stop':
write_file(roster)
diagnosis = input('Enter Diagnosis of patient: ')
first,last = name.split(' ')
roster[last, first] = (diagnosis)
def write_file(roster):
print(roster)
file = open('journal8.txt', 'w')
ir = invert_roster(roster)
print(ir)
wf = json.dumps(ir)
file.write(wf)
file.close()
choice()
def view_file(a):
file = open('journal8.txt', 'r+')
vf = (read_file(file))
print(vf)
keys = vf.keys()
print(keys)
print(type(vf))
for c in vf:
print(c, vf[c])
for c in vf:
vf[c] = tuple(vf[c])
print(vf)
ta = json.dumps(vf)
invert = invert_roster(ta)
file.close()
return()
def read_file(rf):
line = rf.readline()
fin = line.strip()
rf = json.loads(fin)
return(rf)
def new_file():
file = open('journal8.txt', 'w')
return()
choice(a)
The issue seems to be in f(x)=view_file and f(x)=invert_roster. I'm able to convert to string and write to file, read the file and manipulate data from the file, but I can't invert the darn thing.

Why the context of the file cannot read from the txt file?

I have creat a new empty txt file, but the code below read and write it.
f = open('users.txt', 'r+')
users = eval(f.read()) #f.read()read a string,eval()transfer string to dict
for i in range(4):
name = input('Input Username: ')
passwd = input('Input password: ')
c_passwd = input('Confirm password again: ')
if len(name.strip()) != 0 and name not in users and len(passwd.strip()) != 0 and passwd == c_passwd:
users[name]= {'passwd':passwd, 'role':1} #insert new data, role 1: Customer; role 2: Restaurant; role 3: Admin
f.seek(0)
f.truncate() #clear file
f.writelines(str(users)) #write data to file from dict
print('Congratulations, Register Success. ')
f.close()
break
elif len(name.strip()) == 0:
print('Username could not be empty. Remain %d chance' %(3-i))
elif name in users:
print('Username repeat. Remain %d chance' %(3-i))
elif len(passwd.strip()) == 0:
print('Password could not be empty. Remain %d chance' %(3-i))
elif c_passwd != passwd:
print('Password not same. Remain %d chance' %(3-i))
#log in
f = open('users.txt', 'r', encoding='utf8')
users = eval(f.read())
for count in range(3):
name = input('Input Username: ')
password = input('Input password: ')
if name in users and password == users[name]['passwd']:
print('Log in successful!')
break
else:
print('Username or/and Password is/are wrong,You still have %d chance'%(2-count))
f.close()
The System showed
Traceback (most recent call last):
File "C:/Users/zskjames/PycharmProjects/Fit5136/Register, log in.py", line 4, in <module>
users = eval(f.read()) #f.read()read a string,eval()transfer string to dict
File "<string>", line 0
^
SyntaxError: unexpected EOF while parsing
Do anybody could tell me how to fix that? And how to avoid this mistakes in the future.
You probably want your text file to contain JSON, in order to easily interact with it and turn it into a dict.
In order to do that, you would need to replace your eval with a json.load:
import json
with open('users.txt', 'r+') as f:
users = json.load(f)
# rest of your code
In order for it to work, your text file should look something like the following:
{"John Doe": {"passwd": "somepass", "role": 1}}
In addition, you need to replace:
f.writelines(str(users)) #write data to file from dict
to:
json.dump(users, f)

Change text in file with Python

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

Categories

Resources