Search content from a file dictionary in python - python

I have file (dictionary) and I want to search a specific content from a file, how to write the query?
def name_search():
target = open("customers.txt",'r')
name_search = input('Search >')
for line in target:
if name_search in line:
print(f'{name_search} in record!')
else:
print('Not in record!')
The above code works, however, it tries to print this line multiple times depending how many lines I have in file. Assuming the line is not present:
Not in record!
Not in record!
Not in record!
Not in record!

If you are saying you do not want to print multiple times, only once at the end of reading the whole file, then do something like this:
def name_search():
target = open("customers.txt",'r')
name_search = input('Search >')
found = False # use this to remember if we found something
for line in target:
if name_search in line:
print(f'{name_search} in record!')
found = True # remember we found it!
break # this kicks you out of the loop, so you stop searching after you find something
if not found:
print('Not in record!') # only prints this if we didn't find anything
Alternatively, and in fewer lines of code, you can use a return statement in the "found" case. There are reasons people like to avoid having multiple return points in their code, but I present it here as an option:
def name_search():
target = open("customers.txt",'r')
name_search = input('Search >')
for line in target:
if name_search in line:
print(f'{name_search} in record!')
return # kicks us out of the function after we find something
print('Not in record!') # still only prints this if we didn't find anything

Related

Function works if I put in the correct input initially, but if I try a wrong input and then enter the correct input, it gives me an attribute error

I have a try/except statement:
def get_file():
myfile = input("Enter the name of the file to read:\n")
try:
open_myfile = open(myfile, "r")
return open_myfile
except:
print('Could not open file.')
get_file()
And then a function if the code works to check the spelling:
def checktext(textfile):
sp = spellchecker(textfile)
lines_text = textfile.readlines()
true = 0
false = 0
for line in lines_text:
for word in line.split():
c_word = sp.check(word)
if c_word == True:
true =+ 1
else:
print("Possible Spelling Error on line", lines_text.index(line),":",c_word)
false = false + 1
percent = ((true)/(true+false))*100
print(false, "words that passed the spell checker.")
print(true, "words failed the spell checker.")
print(percent, "% of words passed.")
This works if I input a usuable file initially. If I put input anything other than a usable file, it will allow me to input another usable file, however, the code then will give me the attribute error:
'NoneType' object has no attribute 'readlines'. I am not sure why the code works when I just put in the correct file and then doesn't if get_file() passes though the except statement.

input in a function and remove lines from a file

I'm trying to make a modules and for one of the commands I need it to remove a specified user. I need help with it finding the line the user is at. Then deleting the username. Here is the code.
def delete_usr(usr):
file = open("Username.txt","r+")
count = 0
userfound = False
try:
for user in file.readlines():
count += 1
if usr == user.strip():
userfound = True
BTW i also need it to delete the password. The password has the same line as the username and is kept in password.txt
The closest solution to your suggestion would be:
def delete_usr(usr):
file = open("Username.txt","r+")
count = 0
userfound = False
for user in file.readlines():
#print(user.strip())
count += 1
if usr == user.strip():
userfound = True
#print("yeah")
#break
file.close()
If you use a try statement, you expect a perticular kind of error (eg. key not in a dictionary) and also should write except statement to catch the error.
If you use open(file), it is a good practice to also use file.close(). If you use the with statement, as in the example above, you don't need to do it as it is done automatically.
This should do the trick (as long as the user is only on a single line, else remove the break statement):
def delete_usr(usr):
with open("Username.txt","r") as myfile:
lines = myfile.readlines()
for idx, l in enumerate(lines):
if usr==l.split(':')[0]:
lines[idx] = ''
break
with open("Username.txt","w") as myfile:
[myfile.write(i) for i in lines]

How to fix EOF error when reading user input in python 3?

I need to read multiple lines from user input, parse them as commands and call functions. I keep getting EOFError even after I have threw an exception. Same thing happens if I put the if..else statements inside 'try'. The program stops at main and wouldn't call the functions.
EDITED
infile = open('file.csv')
weather = list()
for line in infile:
parse_one_line() #parse each row into tuples
#and add them into a list
while True:
try:
input_stream = input()
command = input_stream.split()
except ValueError:
pass
if command == []:
pass
elif command[:4] == ['filter', 'TEMP', 'at', 'least']:
filterRecord() #user input "filter TEMP at least <integer>"
elif ...
def filterRecord(): #filter rows that meet
#the criteria into a new list
global filtered
filtered = list()
try:
for x in range(len(weather)):
if int(weather[x][2]) >= int(command[-1]):
print(weather[x])
filtered.append(tuple(weather[x]))
except ValueError:
pass
The problem is probably with this line
elif: command == '..'
The colon is in the wrong place, change it to
elif command == '..':

complex iteration over a string in python

The aim of this code is to go through the users input check if check if any of the words match the words on the dictionary then give one response related to the first word that matches and if not reply with "I am curious tell me more". My problem is that I can't iterate over the list and print a single response.
def main():
bank = {"crashed":"Are the drivers up to date?","blue":"Ah, the blue screen of death. And then what happened?","hacked":"You should consider installing anti-virus software.","bluetooth":"Have you tried mouthwash?", "windows":"Ah, I think I see your problem. What version?","apple":"You do mean the computer kind?","spam":"You should see if your mail client can filter messages.","connection":"Contact Telkom."}
def welcome():
print('Welcome to the automated technical support system.')
print('Please describe your problem:')
def get_input():
return input().lower().split()
def mainly():
welcome()
query = get_input()
while (not query=='quit'):
for word in query:
pass
if word in bank:
print(bank[word])
elif not(word=="quit"):
print("Curious, tell me more.")
query = get_input()
mainly()
if __name__=="__main__":
main()
In your code there is few mistakes. First one, when you start the script you run main which loading a local disctionnary 'bank' which does't exist out of the function. When the function end, it runs 'mainly' but doesn't remember the dictionary.
Second one, as you use a dictionnary structure you don't need to loop thru and check all elements 1 by 1. You can instead use the function dict.get
I can propose you this solution :
def welcome():
print('Welcome to the automated technical support system.')
print('Please describe your problem:')
def get_input():
return input().lower().split()
def main():
bank = {"crashed": "Are the drivers up to date?", ...}
welcome()
query = get_input()
while query != 'quit':
if bank.get(query, None) is not None:
print(bank[query])
else:
print("doesn't exist")
query = get_input()
print("Curious, tell me more.") # will be triggered only when you are out of the loop
if __name__=="__main__":
main()
In that case bank.get(query, None) will return the sentence if the word exist, else it returns None.
You can also simplify it as :
while query != 'quit':
sentence = bank.get(query, "doesn't exist")
print(bank[query])
query = get_input()
this is because if it exist, sentence = what you want to display, if it doesn't, it displays the error message you want
I hope it helps,

Python Spell Check With Suggestions

I have a program that I'm working on that takes an input and checks it to see if it spelled correctly with a dictionary inside of a file. However, I want to return a suggestion or two as well of what the person means. Any suggestions of how to do this? I have found some modules that can do it, but not for a specific dictionary from a file. Any help is appreciated!!
Here is what I have now:
def getDictionary():
theDictionary = open("theDictionary.txt", "r")
dictionaryList = []
for eachLine in theDictionary:
splitLines = eachLine.split()
dictionaryList.append(splitLines[0])
theDictionary.close()
return dictionaryList
def spellChecker(theFile, theDictionary):
lowerItems = theFile.lower()
wordList = lowerItems.split()
wrongList = []
for item in wordList:
if item not in theDictionary:
result = False
wrongList.append(item)
else:
result = True
wrongItem = ""
return (result, wrongList)
def main():
theDictionary = getDictionary()
theText = getFile()
theInput = input("Input some words here:")
result, wrongList=spellChecker(theInput,theDictionary)
if result:
print("There are no spelling errors in the sentence! Hooray!")
else:
if len(wrongList) == 1:
print('There is a spelling error in the sentence! The word that is wrong is "' + str(wrongList) + '".')
elif len(wrongList) > 1:
print('There are some spelling errors in the sentence! The words that are wrong are"' + str(wrongList) + '".')
main()
You might want to have a look at the difflib module in the Standard Library. It allows you to do approximate string matching, which seems to be what you want.
It really does not matter if your dictionary is inside a file or not, since you are loading it into a list anyway. Maybe have a look at the get_close_matches() method in the said module.

Categories