Compare user input string to text file python - python-3.x

I have a text file filled with sample usernames and I would like to compare it to a user input to see if there is a match. If content matches it will return "This is a match" and if not it will return "That is not a match."
filename = 'UserNames.txt'
with open(filename) as f_obj:
nameLists = f_obj.read()
name = input("Enter a username: ")
if name in nameLists:
print(name + " is a match" )
else:
print( name + "is not a match")
This worked to a degree but will return is a match if the user entered something similar. Ex: text file has blizz1730, user enters blizz. It comes out as a match

You can split the words with spaces and compared with each word to find the match.
name = 'blizz'
nameLists='wla asdnfas blizz1730'
if name in nameLists.split():
print(name + " is a match" )
else:
print( name + " is not a match")
output:
blizz is not a match

Related

Searching for a wildcard pattern in a text file in Python

I am trying to search for similar words in Python given a wildcard pattern, for example in a text file similar to a dictionary- I could search for r?v?r? and the correct output would be words such as 'rover', 'raver', 'river'.
This is the code I have so far but it only works when I type in the full word and not the wildcard form.
name = input("Enter the name of the words file:\n"
pattern = input("Enter a search pattern:\n")`
textfile = open(name, 'r')
filetext = textfile.read()
textfile.close()
match = re.findall(pattern, filetext)
if match is True:
print(match)
else:
print("Sorry, matches for ", pattern, "could not to be found")
Use dots for blanks
name = input("Enter the name of the words file:\n"
pattern = input("Enter a search pattern:\n")`
textfile = open(name, 'r')
filetext = textfile.read()
textfile.close()
re.findall('r.v.r',filetext)
if match is True:
print(match)
else:
print("Sorry, matches for ", pattern, "could not to be found")
Also, match is a string, so you want to do
if match!="" or if len(match)>0
,whichever one suits your code.

newbie python - adding 'cilent' into the txt file

I'm working on a registration in my school project, and one part of it is about registartion. I have to input client in form of
username
password
name
lastname
role
so he can be registered and appended into the txt file,
but i also have to make "username" be the unique in file (because I will have the other cilents too) and "password" to be longer than 6 characters and to possess at least one number.
Btw role means that he is a buyer. The bolded part I didn't do and I need a help if possible. thanks
def reg()
f = open("svi.txt","a")
username = input("Username: ")
password = input("Password: ")
name = input("Name of a client: ")
lastname = input("Lastname of a client: ")
print()
print("Successful registration! ")
print()
cilent = username + "|" + password + "|" + name + "|" + lastname + "|" + "buyer"
print(cilent,file = f)
f.close()
You need to add some file parsing and logic in order to accomplish this. Your jobs are to:
1: Search the existing file to see if the username exists already. With the formatting as you've given it, you need to search each line up to the first '|' and see if the new user is uniquely named:
name_is_unique = True
for line in f:
line_pieces = line.split("|")
test_username = line_pieces[0]
if test_username == username:
name_is_unique = False
print("Username already exists")
break
2: See if password meets criteria:
numbers=["0","1","2","3","4","5","6","7","8","9"]
password_contains_number = any(x in password for x in numbers)
password_is_long_enough = len(password) > 6
3: Write the new line only if the username is unique AND the password meets your criteria:
if name_is_unique and password_contains_number and password_is_long_enough:
print(cilent,file = f)
Edit: You may also have to open it in reading and writing mode, something like "a+" instead of "a".

Writing files with limited user-prompt inputs

I need a code that prompts the user for a name and a number, but the maximum is 3. Then it will write the code to an empty text file, even though the names are only 2 or 3.
name = True
while name:
if name == "done entering":
name = False
break
else:
name = True
firstName1 = input("Enter your first Name: ")
lastName1 = input("Enter your last Name here: ")
studentID1 = input("Enter your id number: ")
firstName2 = input("Enter your first Name: ")
lastName2 = input("Enter your last Name here: ")
studentID2 = input("Enter your id number: ")
firstName3 = input("Enter your first Name: ")
lastName3 = input("Enter your last Name here: ")
studentID3 = input("Enter your id number: ")
break
inFile = open("studentInfo.txt", 'a')
inFile.write("Name: " + firstName1 + " " + lastName1)
inFile.write("\nStudentID: " + studentID1)
inFile.write("Name: " + firstName2 + " " + lastName2)
inFile.write("\nStudentID: " + studentID2)
inFile.write("Name: " + firstName3 + " " + lastName3)
inFile.write("\nStudentID: " + studentID3)
inFile.close()
print("\nDone! Data is saved in file: studentInfo.txt")
I copy-pasted my first code and it kind of works, but whenever I run it in the Python interpreter, there is a "y" before the "enter first names" and I can't enter 2 names only, it requires 3. And how can I make that shorter too... TY
I cannot reproduce the "y" before the "enter first names" behavior. Perhaps a
copy and paste issue in your environment.
To enter less than 3 entries then you need something to limit to 3 and can
allow less than 3. This may need different data handling like using a list.
Create a list to store the 3 groups of entries. A list has length, so use
the length of the list as the while statement. The loop will end after 3 groups
of entries.
Break from the loop if the first name entry is empty as that implies no more
input. Continue the loop if other items are empty so the user can redo the group.
Append the group of entries into the list at end of each loop.
These conditions of break or continue may be changed if preferred.
When the loop ends, if the list is empty then end the script as nothing to do.
Writing the file can be done with a for loop. Use a formatted string so the
group can be written as one group. Formatting allows for further alignment etc.
studentInfo = []
while len(studentInfo) < 3:
firstName = input("Enter your first Name: ")
if firstName == '':
break
lastName = input("Enter your last Name here: ")
if firstName == '':
continue
studentID = input("Enter your id number: ")
if studentID == '':
continue
studentInfo.append([firstName, lastName, studentID])
print()
if not studentInfo:
exit()
fileName = "studentInfo.txt"
inFile = open(fileName, 'a')
for firstName, lastName, studentID in studentInfo:
inFile.write("Name: {} {}\n"
"StudentID: {}\n"
.format(firstName, lastName, studentID)
)
inFile.close()
print("Done! Data is saved in file: " + fileName)

Searching Names and phonenumbers

mine is homework question in response to the previous Question i posted on this site:
i redid the code to the following:
import re
people = ["Karen", "Peter", "Joan", "Joe", "Carmen", "Nancy", "Kevin"]
phonenumbers = ["201-222-2222", "201-555-1212", "201-967-1490", 201-333-3333",'201-725-3444", "201-555-1222", "201-444-4656"]
name = raw_input("Enter person's name:")
found = false
for i in range(0, len(people)):
value = people[i]
m = ("(" + name + ".*)",value)
if m:
found = True
print (people[i], phonenumber[i])
else:
print ("No matching name was found.")
My question is how do i tell the program to check if Karen's phone number is the 201-222-2222? And Yes this is a homework assignment. I changed the names and the phone numbers in my acutal program.
When i run this program and type any character all the names and phone number show up that's where i'm having difficutly...
EDITED: Question isn't clear to me.
The following code my help.
1.) First it ask for name then check if it exist in the people list.
2.) Then if it exist it saves it in variable called abc.
3.) After loop is finished it prints the abc which is the name you entered and that person phone number.
import re
people = ["Karen", "Peter", "Joan", "Joe", "Carmen", "Nancy", "Kevin"]
phonenumbers = ["201-222-2222", "201-555-1212", "201-967-1490", "201-333-3333","201-725-3444", "201-555-1222", "201-444-4656"]
name = input("Enter person's name:")
abc = "" # Will store the name and phone number
found = False
for i in range(0, len(people)):
if people[i].lower() == name.lower(): #checks if input name match + use method to lower all char
abc = people[i]+" Has the number "+phonenumbers[i]
value = people[i]
m = ("(" + name + ".*)",value)
if m:
found = True
print (people[i], phonenumbers[i]) # missing letter "s"
else:
print ("No matching name was found.")
print("\n"+abc)
Result

Creating a autocorrect and word suggestion program in python

def autocorrect(word):
Break_Word = sorted(word)
Sorted_Word = ''.join(Break_Word)
return Sorted_Word
user_input = ""
while (user_input == ""):
user_input = input("key in word you wish to enter: ")
user_word = autocorrect(user_input).replace(' ', '')
with open('big.txt') as myFile:
for word in myFile:
NewWord = str(word.replace(' ', ''))
Break_Word2 = sorted(NewWord.lower())
Sorted_Word2 = ''.join(Break_Word2)
if (Sorted_Word2 == user_word):
print("The word",user_input,"exist in the dictionary")
Basically when I had a dictionary of correctly spelled word in "big.txt", if I get the similar from the user input and the dictionary, I will print out a line
I am comparing between two string, after I sort it out
However I am not able to execute the line
if (Sorted_Word2 == user_word):
print("The word",user_input,"exist in the dictionary")
When I try hard code with other string like
if ("a" == "a"):
print("The word",user_input,"exist in the dictionary")
it worked. What wrong with my code? How can I compared two string from the file?
What does this mean? Does it throw an exception? Then if so, post that...
However I am not able to execute the line
if (Sorted_Word2 == user_word):
print("The word",user_input,"exist in the dictionary")
because I can run a version of your program and the results are as expected.
def autocorrect(word):
Break_Word = sorted(word)
Sorted_Word = ''.join(Break_Word)
return Sorted_Word
user_input = ""
#while (user_input == ""):
user_input = raw_input("key in word you wish to enter: ").lower()
user_word = autocorrect(user_input).replace(' ', '')
print ("user word '{0}'".format(user_word))
for word in ["mike", "matt", "bob", "philanderer"]:
NewWord = str(word.replace(' ', ''))
Break_Word2 = sorted(NewWord.lower())
Sorted_Word2 = ''.join(Break_Word2)
if (Sorted_Word2 == user_word):
print("The word",user_input,"exist in the dictionary")
key in word you wish to enter: druge
user word 'degru'
The word druge doesn't exist in the dictionary
key in word you wish to enter: Mike
user word 'eikm'
('The word','mike', 'exist in the dictionary')
Moreover I don't know what all this "autocorrect" stuff is doing. All you appear to need to do is search a list of words for an instance of your search word. The "sorting" the characters inside the search word achieves nothing.

Resources