Re module not working for computer science coursework - python

So I am trying to use the re module to see if a number plate matches with how a number plate should be, but I keep getting errors with the module, my code is below.
def nplatec():
import re
r_plate = "^[Aa-Zz]{2}[0-9][Aa-Zz]{3}$"
while True:
u_plate = input("Enter your number plate WITHOUT spaces please : ")
a_speed = int(input("Enter you average speed : "))
s_limit = 70
if re.match(r_plate, u_plate):
print("InCorrect number plate")
break
nplatec()
Errors:

I found the answer, its meant to be "^[A-Za-z]{2}[0-9][A-Za-z]{3}$" rather than "^[Aa-Zz]{2}[0-9][Aa-Zz]{3}$"

Related

Python & API user input

My code is
import requests
from pprint import pprint
from pip._vendor.distlib.compat import raw_input
recipe_ingredients = input("What is the recipe ingredients? ")
number_recipes = input("How many recipes do you want? ")
url = 'https://api.spoonacular.com/recipes/findByIngredients?ingredients={}&number={}&'.format(recipe_ingredients,number_recipes)
response = requests.get(url)
print(response)
However, when I am inputting more than one ingredient in the format of (two ingredients) cheese and potato it is returning results for either the first variable or tells me there is a syntax error with and.
Is there any way I am able to program my search function to accept and ,whereby it can display all the results for both words, as it is likely a user will put 'and' within their search for more than one ingredient.
( I am using pycharm btw)
You are only requesting one string from the user. Whenever you try to enter 2 strings separated by Enter, the second string cannot be saved and thus the exception.
You may fix it like:
n = int(input("Number of ingredients: "))
recipe_ingredients = []
print("Enter " + str(n) + " recipe ingredients")
for i in range(n):
recipe_ingredients.append(input())

Can I input a variable that can input only a name with space?

I am using python 3.6.5
I want to input a variable which can take in name of the person with space. This is my code for it right now:
def addition():
with open('Directory.csv','a',newline='') as file:
w=csv.writer(file,delimiter=',')
def names():
name=input('Enter Name :')
n=0
for i in name:
if i.isalpha() or i.isspace():
n+=0
else:
n+=1
if n==0:
return name
else:
print('Error')
return names()
name=names()
But when I press enter without any value inputted, it still accepts it:
Enter Value of k : 2
Enter Name :
Enter Year of Birth :
What should be my code to correct this?
The basic problem here is that the loop for i in name: won't run if name is empty, leaving n at zero. The least invasive way to fix this is to check in the subsequent if:
if name and n == 0:
There are other improvements I'd recommend, starting with removing the recursive call in favor of a loop. A user could trigger a stack overflow by typing in bad characters enough times.
Rather than counting bad characters, you can break out of the loop early. This removes your dependence on n entirely:
def names():
while True:
name = input('Enter Name: ')
if name:
for i in name:
if not i.isalpha() or not i.isspace():
break
else:
return name
print('Error')
The else clause here is correctly matched to the for loop. It's a neat python trick for running code only if the loop didn't break.
There are less manual ways to check that a string contains only letters and spaces. The most popular likely being regular expressions, which are supported by the standard library. This would be a simple regex:
import re
...
name_pattern = re.compile('[a-zA-Z ]+')
...
def names():
while True:
name = input('Enter Name: ').strip()
if name_pattern.fullmatch(name):
return name
print('Error')

How do I reset to the beginning of the code after it runs? [duplicate]

This question already has answers here:
How to make program go back to the top of the code instead of closing [duplicate]
(7 answers)
Asking the user for input until they give a valid response
(22 answers)
Closed 3 years ago.
After the code runs all the way for the first time, I want it to be able to go back to the first input and allow the user to input another word.
Do I need to create a for or while loop around the program?
import re
import requests
search = input('What word are you looking for?: ')
first = re.compile(search)
source = input ('Enter a web page: ')
r = requests.get(source)
ar = r.text
mo = first.findall(ar)
print (mo)
print('Frequency:', len(mo))
Yes, a loop is needed:
import re
import requests
while True:
search = input('What word are you looking for?: ')
# per comment, adding a conditional stop point.
if search == "stop":
break
first = re.compile(search)
source = input ('Enter a web page: ')
r = requests.get(source)
ar = r.text
mo = first.findall(ar)
print (mo)
print('Frequency:', len(mo))
Yep a while look is the way to go.
Make sure you don't have an infinite loop though. (You want some way to break out...
I would recommend just adding this to the search, so if they type exit it breaks out of the look. I have also added .lower() so Exit, EXIT, etc also work.
import re
import requests
while True:
search = input('What word are you looking for?: ')
if search.lower() == "exit": #break out of the loop if they type 'exit'
break
first = re.compile(search)
source = input ('Enter a web page: ')
r = requests.get(source)
ar = r.text
mo = first.findall(ar)
print (mo)
print('Frequency:', len(mo))

How to read input line by line, instead of by spacing

I'm trying to read a large number of user inputs line by line instead of by spacing.
code:
keyword = (input("\n Please enter the keywords "))
keywords = keyword.split(" ")
words:
a
abandon
ability
able
abortion
The input function ends by pressing enter or moving to a new line, so you have to define how you want to finish instead.
If you're looking for a way to enter 5 words like you did in your example, this should be enough:
print("\n Please enter the keywords ")
keywords = [input() for i in range(5)]
You can change range(5) to range(3000) or any other number that you wish.
If you would like in input an infinite amount of words until some special keyword is entered (like "quit") you can do this:
print("\n Please enter the keywords ")
keywords = []
while True:
k = input()
if k == 'quit':
break
else:
keywords.append(k)
You may want to read from the sys.stdin, for example:
import sys
it = iter(sys.stdin)
while True:
print(next(it))
Here you have a live example

search data in file using python?

i have a file file.txt i want to search a data in a file using phone number for example if i entered 996452544 then result will be Alex 996452544 alex#gmail how to do that in python i do not know i am newbie help me.
file.txt
Alex 996452544 alex#gmail
Jhon 885546694 jhon#gmail
Arya 896756885 arya#gmail
code.py
def searchContact():
number=raw_input("Enter phone number to search data : ")
obj1=open("file.txt","r")
re=obj1.read()
print re
obj1.close()
searchContact()
def searchContact():
obj1 = open("address.txt","r")
number = raw_input("Enter phone number to search data : ")
for line in obj1.readlines():
if number in line:
print line
obj1.close()
hope this help. If yes accept and upvote
def searchContact():
number=raw_input("Enter phone number to search data : ")
obj1=open("file.txt","r")
re=obj1.read()
print re
x= re.split("\n")
matching = [s for s in x if number in s]
print matching
obj1.close()
searchContact()
This simple code will do the work
def searchContact():
number=raw_input("Enter phone number to search data : ")
obj1=open("file.txt","r")
for line in obj1.readlines():
if number in line:
print(line)
obj1.close()
I hope this will help you
for line in obj1.readlines():
if number in line:
print line

Categories

Resources