My python program is giving unexpected results within the regular expressions functions, when I enter a number plate for recognition, it tells me it's invalid, although it is valid and I don't know why?
I would be grateful if you could tell me what's wrong and give a possible solution, as this is a very important homework assignment.
#Start
#04/02/2016
bad=[]#initialise bad list
data="Y"#initialise value to prevent infinite loop
standardNumberPlateObj=""
NumPlate=""
import re#import re functions
import pickle#import pickle function
print ("Welcome to the number plate recognition program.\n\n")
choice=input("Press 1 to input number plates and save\nPress 2 to read binary number plate file: ")
if choice == "1":
while data=="Y":# while loop
NumPlate = input("Input Registration number in format (XX01 XXX) *With a space at the end!*:\n\n") #user input for numberplate
standardNumberPlateObj=re.match(r'\w\w\d\d\s\w\w\w\s', NumPlate, re.M|re.I)#validate that numberplate is valid
if standardNumberPlateObj:
print("Verification Success")
data=input(str("Would you like to continue? (Y/N):"))
else:
print("Verification Failed")
bad.append(NumPlate)#add numberplate to bad list
data=input(str("Would you like to continue? (Y/N):"))#ask user to continue
while data=="N":#saving number plates to file if user enters N
f = open("reg.dat", "wb")
pickle.dump(bad, f)
f.close()
print ("\nRestart the program to read binary file!")#ending message
break
elif choice == "2":
print ("\nBad number plates:\n\n")
f=open("reg.dat", "rb")
Registrations = pickle.load(f)
print(Registrations)
f.close()
else:
print ("Please enter a valid choice!")
print ("\n END of program!")
It's not really possible to tell without an example input and the expected and the actual result.
But judging from the expression \w\w\d\d\s\w\w\w\s and your example in the prompt (XX01 XXX), I'd say that your regular expression is expecting a space in the end, while your input doesn't provide one.
Related
I have to write a program that takes user input for a website and keyword, and then reads the source code of the website for that word. I have to code it so it detects many variations of the word (ex. hello vs. hello, vs. hello!) and am not sure how to do this. I have it coded like this so far to detect the exact input, but I'm not sure how to get multiple variations. Any help would be greatly appreciated, thank you!
def main():
[n,l]=user()
print("Okay", n, "from", l, ", let's get started.")
webname=input("What is the name of the website you wish to browse? ")
website=requests.get(input("Please enter the URL: "))
txt = website.text
list=txt.split(",")
print(type(txt))
print(type(list))
print(list[0:10])
while True:
numkey=input("Would you like to enter a keyword? Please enter yes or no: ")
if numkey=="yes":
key=input("Please enter the keyword to find: ")
else:
newurl()
break
find(webname,txt,key)
def find(web,txt,key):
findtext=txt
list=findtext.split(sep=" ")
count = 0
for item in list:
if item==key:
count=count+1
print("The word", key, "appears", count, "times on", web)
def newurl():
while True:
new=input("Would you like to browse another website? Please enter yes or no: ")
if new=="yes":
main()
else:
[w,r]=experience()
return new
break
def user():
name=input("Hello, what is your name? ")
loc=input("Where are you from? ")
return [name,loc]
def experience():
wordeval=input("Please enter 3 words to describe the experience, separated by spaces (ex. fun cool interesting): ")
list=wordeval.split(sep=" ")
rate=eval(input("Please rate your experience from 1-10: "))
if rate < 6:
print("We're sorry you had a negative", list[0], "and", list[2], "experience!")
else:
print("Okay, thanks for participating. We're glad your experience was", list[1], "!")
return[wordeval,rate]
main()
What you're looking for is the re module. You can get indices of the matches, individual match instances, etc. There are some good tutorials here that you can look at for how to use the module, but looping through the html source code line by line and looking for matches is easy enough, or you can find the indices within the string itself (if you've split it by newline, or just left it as one long text string).
I am writing a code that basically asks for user input of an 8 digit number, that is then read from a text file to see if it is valid and then asks the user for quantity. It works fine up until it needs to calculate the total of the product (multiplied by quantity entered)? It produces this error:
Traceback (most recent call last):
File "C:\Users\User\Desktop\A453 Task 2.py", line 25, in <module>
price=float(itemsplit[2]) #price is
ValueError: could not convert string to float: 'magent,'
Here is my actual code:
loop=1
while loop==1:
print ("The Hardware Store")
print ("a - Place an order by barcode")
print ("x - Exit")
task=input("Please make your selection")
if task.lower()=="a":
print("The Hardware Store")
myfile=open("hardware_store.txt", "r") #this opens the text file
product_information=myfile.readlines() #reads the file and stores it
as a variable named variable 'details'
myfile.close() #closes the file
while True:
digits=input("Please enter your GTIN-8 code\n")
if len(digits) !=8: #if the digits aren't equal to 8 digits, the
input not accepted
print("Please enter a valid GTIN-8 code\n")
else:
break #if the code is the correct length, the loop ends
for line in product_information:
if digits in line:
productline=line
myfile=open("receipt.txt", "w") #opens receipt file
myfile.writelines("\n" + "+")
quantity=input("How much of the product do you wish to purchase?\n")
itemsplit=line.split(' ') #seperates into different words
price=float(itemsplit[2]) #price is
total=(price)*(quantity) #this works out the price
myfile.writelines("Your total spent on this product is: " +str("£:,.2f)".format(total)+"\n"))
if task.lower()=="x":
print("Thank you for visiting the hardware store, come again!")
break
else:
print("Sorry, please enter a valid input")
And here is the text file (named "hardware_store.txt")
16923577,Hammer,3.00,
78451698,32 lrg nails,2,
17825269,32 med nails,2.00,
58246375,32 sml nails,2.00,
21963780,Drill Bits set,7.00,
75124816,Lrg Brush,2.00,
78469518,Sml Brush,1.00,
58423790,Dust Pan,1.00,
88562247,32 lrg screws,2.00,
98557639,32 med screws,2.00,
37592271,32 sml screws,2.00,
50966394,screwdriver set,7.00,
75533458,wall bracket,0.70,
12345678, neodymium magent, 9.99
10101010, screws 12x50mm Pack 50, 2.79
I don't understand what is happening, it works up until you enter the desired quantity. Thanks in advance
You file hardware_store.txt has values separated on each lines by comma, not whitespace. You should split the line by ',', not by ' '.
You could also look at the CSV module in python to read your file.
In itemsplit list you have:
itemsplit[0] = "12345678,"
itemsplit[1] = "neodymium"
itemsplit[2] = "magent,"
itemsplit[3] = "9.99"
itemsplit[2] hasn't got any number to cast float.
You must use try ... except ... to catch the exception when no number is in your list item.
I've corrected your code:
so say we have a hardware_store.txtfile that contains:
12345678 5
task = ""
while task.lower() != "x":
print ("The Hardware Store")
print ("a - Place an order by barcode")
print ("x - Exit")
task=input("Please make your selection ")
if task.lower()=="a":
print("The Hardware Store")
myfile=open("hardware_store.txt", "r") #this opens the text file
product_information=myfile.readlines() #reads the file and stores it as a variable named variable 'details'
myfile.close() #closes the file
while True:
digits=input("Please enter your GTIN-8 code\n")
if not len(digits) == 8: #if the digits aren't equal to 8 digits, the input not accepted
print("Please enter a valid GTIN-8 code\n")
else:
break #if the code is the correct length, the loop ends
for line in product_information:
if digits in line:
#productline=line
myfile=open("receipt.txt", "w") #opens receipt file
myfile.write("\n" + "+")
quantity=input("How much of the product do you wish to purchase?\n")
quantity = int(quantity)
price = line.split(" ")[1]
price=float(price) #price is
total=(price)*(quantity) #this works out the price
myfile.write("Your total spent on this product is: £:({:.2f}){}".format(total, '\n'))
myfile.close()
else:
print("Sorry, please enter a valid input")
else:
print("Thank you for visiting the hardware store, come again!")
Running the code:
The Hardware Store
a - Place an order by barcode
x - Exit
Please make your selection a
The Hardware Store
Please enter your GTIN-8 code
12345678
How much of the product do you wish to purchase?
5
The Hardware Store
a - Place an order by barcode
x - Exit
Please make your selection x
Thank you for visiting the hardware store, come again!
receipt.txt:
\n
+Your total spent on this product is: £:(25.00)
You won't see \n in your text editor if you open receipt.txt, I've included the '\n' just to make it clear that there's a new line at the beginning, you'll just see an empty space in your editor followed by +Your reset of the text...
I want to prompt the user to input specific data from a text file(keys) so my dictionary can give the value for each of them.
It works like this:
fin=open('\\python34\\lib\\toys.txt')
toys = {}
for word in fin:
x=fin.readline()
x = word.replace("\n",",").split(",")
a = x[0]
b=x[1]
toys[a]=str(b)
i = input("Please enter the code:")
if i in toys:
print(i," is the code for a= ", toys[i],)
else:
print('Try again')
if i == 'quit':
break
but it prints 'try again' if I input a random key from my list. (which is the following:
D1,Tyrannasaurous
D2,Apatasauros
D3,Velociraptor
D4,Tricerotops
D5,Pterodactyl
T1,Diesel-Electric
T2,Steam Engine
T3,Box Car
T4,Tanker Car
T5,Caboose
B1,Baseball
B2,Basketball
B3,Football
B4,Softball
B5,Tennis Ball
B6,Vollyeball
B7,Rugby Ball
B8,Cricket Ball
B9,Medicine Ball
but if I do it in order it works. How can I fix this program so I can input any key at any time and it will still print its corresponding value?
You need to read in the whole file before prompting for your search term. So you'll need two loops -- one to get the whole data in, and a second loop to search through he data.
Here's what your updated code will look like. I replaced the file input with an array so that I could run it using a web tool:
fin=['D1,Tyrannasaurous','D2,Apatasauros','D3,Velociraptor' ]
toys = {}
for word in fin:
x = word.replace("\n",",").split(",")
a = x[0]
b=x[1]
toys[a]=str(b)
while 1:
i = input("\nPlease enter the code:")
if i in toys:
print(i," is the code for a= ", toys[i],)
else:
print('\nTry again')
if i == 'quit':
break
Output here: https://repl.it/BVxh
To read the file into dictionary:
with open('toys.txt') as file:
toys = dict(line.strip().split(',') for line in file)
To print values corresponding to the input keys provided by a user from a command-line interactively until quit key is received:
for code in iter(lambda: input("Please enter the code:"), 'quit'):
if code in toys:
print(code, "is the code for toy:", toys[code])
else:
print(code, 'is not found. Try again')
It uses two-argument iter(func, sentinel).
This question already has answers here:
While loop user input in range
(2 answers)
Closed 8 years ago.
This is my code:
my_Sentence = input('Enter your sentence. ')
sen_length = len(my_Sentence)
sen_len = int(sen_length)
while not (sen_len < 10 ):
if sen_len < 10:
print ('Good')
else:
print ('Wo thats to long')
break
I'm trying to make the program ask the user continuously to write a sentence, until it is under 10 characters. I need to know how to have the program as for a sentence again, but I think the simplest way would be to have the code start from the top; but I'm not surte how to do that. Can someone help?
The pattern
The general pattern for repeatedly prompting for user input is:
# 1. Many valid responses, terminating when an invalid one is provided
while True:
user_response = get_user_input()
if test_that(user_response) is valid:
do_work_with(user_response)
else:
handle_invalid_response()
break
We use the infinite loop while True: rather than repeating our get_user_input function twice (hat tip).
If you want to check the opposite case, you simply change the location of the break:
# 2. Many invalid responses, terminating when a valid one is provided
while True:
user_response = get_user_input()
if test_that(user_response) is valid:
do_work_with(user_response)
break
else:
handle_invalid_response()
If you need to do work in a loop but warn the user when they provide invalid input then you just need to add a test that checks for a quit command of some kind and only break there:
# 3. Handle both valid and invalid responses
while True:
user_response = get_user_input()
if test_that(user_response) is quit:
break
if test_that(user_response) is valid:
do_work_with(user_response)
else:
warn_user_about_invalid_response()
Mapping the pattern to your specific case
You want to prompt a user to provide you a less-than-ten-character sentence. This is an instance of pattern #2 (many invalid responses, only one valid response required). Mapping pattern #2 onto your code we get:
# Get user response
while True:
sentence = input("Please provide a sentence")
# Check for invalid states
if len(sentence) >= 10:
# Warn the user of the invalid state
print("Sentence must be under 10 characters, please try again")
else:
# Do the one-off work you need to do
print("Thank you for being succinct!")
break
longEnough = false
while not longEnough:
sentence = raw_input("enter a sentence: ") # Asks the user for their string
longEnough = len(sentence) > 10 # Checks the length
I'm a technical writer learning python. I wanted to write a program for validating the Name field input,as a practise, restricting the the user entries to alphabets.I saw a similar code for validating number (Age)field here, and adopted it for alphabets as below:
import string
import re
r = re.compile(r'[a-zA-Z]+')
print "WELCOME FOR NAME VERIFICATION. TYPE ALPHABETS ONLY!"
print raw_input("Your Name:")
x = r
if x == r:
print x
elif x != r:
print "Come on,'", x,"' can't be your name"
print raw_input("Your Name:")
if 5<=len(x)<=10:
print "Hi,", x, "!"
elif len(x)>10:
print "Mmm,Your name is too long!"
elif len(x)<5:
print "Alas, your name is too short!"
raw_input("Press 'Enter' to exit!")
I intend this code block to do two things. Namely, display the input prompt until the user inputs alphabets only as 'Name'. Then, if that happens, process the length of that input and display messages as coded. But, I get two problems that I could not solve even after a lot of attempts. Either, even the correct entries are rejected by exception code or wrong entries are also accepted and their length is processed.
Please help me to debug my code. And, is it possible to do it without using the reg exp?
If you're using Python, you don't need regular expressions for this--there are included libraries which include functions which might help you. From this page on String methods, you can call isalpha():
Return true if all characters in the string are alphabetic and there is at least one character, false otherwise.
I would suggest using isalpha() in your if-statement instead of x==r.
I don't understand what you're trying to do with
x = r
if x == r:
etc
That condition will obviously always be true.
With your current code you were never saving the input, just printing it straight out.
You also had no loop, it would only ask for the name twice, even if it was wrong both times it would continue.
I think what you tried to do is this:
import string
import re
r = re.compile(r'[a-zA-Z]+')
print "WELCOME FOR NAME VERIFICATION. TYPE ALPHABETS ONLY!"
x = raw_input("Your Name:")
while not r.match(x):
print "Come on,'", x,"' can't be your name"
x = raw_input("Your Name:")
if 5<=len(x)<=10:
print "Hi,", x, "!"
elif len(x)>10:
print "Mmm,Your name is too long!"
elif len(x)<5:
print "Alas, your name is too short!"
raw_input("Press 'Enter' to exit!")
Also, I would not use regex for this, try
while not x.isalpha():
One way to do this would be to do the following:
namefield = raw_input("Your Name: ")
if not namefield.isalpha():
print "Please use only alpha charactors"
elif not 4<=len(namefield)<=10:
print "Name must be more than 4 characters and less than 10"
else:
print "hello" + namefield
isalpha will check to see if the whole string is only alpha characters. If it is, it will return True.