Searching Names and phonenumbers - python-3.x

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

Related

Get elements (salutation, title, last name and first name) from string with varying number of elements

I am still at the beginning of my Python journey and need your help with the following task:
After webscraping for contact details, I get a string for the company's CEO. This string contains salutation, title, last name and first name of the CEO. I would like to split this string to the corresponding elements (salutation, title, last name and first name). My problem is that the elements vary greatly, so for example:
with or without salutation
different titles
one or more first names
one or more surnames
The order of the elements is always the same. There is also always only one last name.
#some examples for the string:
ceo1 = "Herr Dr. Mustermann Max" #salutation, titel, last name and first name
ceo2 = "Müller Monika" #just firstname and lastname
ceo3 = "Frau Mustermann Iris Petra" #salutation, last name and 2x first name
ceo4 = "Herr Mag. Dr. Schubert Franz Peter" #salutation, 2x titel, last name and 2x first name
ceo5 = "Herr Dipl.-Ing. BA Mozart Wolfgang Amadeus" #salutation, 2x titel (one without a dot at the end), last name and 2x first name
ceo = ceo2
#get salutation:
salutation_list = ["Herr", "Frau"]
salutation_test = bool(sum(map(lambda x: x in ceo, salutation_list)))
if salutation_test is True:
salutation = ceo[0:4]
ceo_without_salutation = ceo[5:]
else:
salutation = "N/A"
ceo_without_salutation = ceo
#get title:
title_list = ["Dr.", "Mag. Dr.", "BA", "Dipl.-Ing."]
title_test = bool(sum(map(lambda x: x in ceo_without_salutation, title_list)))
if title_test is True:
title = "titel" #How can I extract the corresponding element from the list and eliminate it from string 'ceo_without_salutation'?
ceo_without_title = "ceo_without_salutation - titel"
else:
title = "N/A"
ceo_without_title = ceo_without_salutation
name_list = ceo_without_title.split(" ")
#get lastname
lastname = name_list[0]
#get firstname
del name_list[0]
firstname = "".join(name_list)
Most important question: how can I extract the title? And beyond that, is there a better way than mine to solve the issue? Thanks a lot for your help!
If title is always followed by a 'dot' "." you can use regex positive lookahead (regular expressions).
here is a sample function that gets text and extract the title :
import re
def get_title(text:str):
result = re.search(r'\w+(?=\.)',text)
if result :
return result.group()
Ok, I now have at least a solution that works. If someone knows a more python-ish way, I would be very happy to learn from it. Thanks a lot!
#some ceo-string examples:
ceo1 = "Herr Dr. Mustermann Max" #salutation, titel, last name and first name
ceo2 = "Müller Monika" #just firstname and lastname
ceo3 = "Frau Mustermann Iris Petra" #salutation, last name and 2x first name
ceo4 = "Herr Mag. Dr. Schubert Franz Peter" #salutation, 2x titel, last name and 2x first name
ceo = ceo4
#get salutation:
salutation_list = ["Herr", "Frau"]
salutation_test = bool(sum(map(lambda x: x in ceo, salutation_list)))
if salutation_test is True:
salutation = ceo[0:4]
ceo_without_salutation = ceo[5:]
else:
salutation = "N/A"
ceo_without_salutation = ceo
#get title:
title_list = ["Dr.", "Mag. Dr.", "Dipl.-Ing.", "BA", "MAS"]
title_test = bool(sum(map(lambda x: x in ceo_without_salutation, title_list)))
titles_ceo = []
index_max = []
if title_test is True:
for i in title_list:
x = ceo_without_salutation.find(i)
if x >= 0:
y = ceo_without_salutation.find(" ", x)
z = ceo_without_salutation[x:y]
index_max.append(y)
titles_ceo.append(z)
else:
continue
title = " ".join(titles_ceo)
j = max(index_max)
k = len(ceo_without_salutation)
ceo_without_title = ceo_without_salutation[j+1:k]
else:
title = "N/A"
ceo_without_title = ceo_without_salutation
#get firstname and lastname:
m = ceo_without_title.find(" ")
lastname = ceo_without_title[0:m]
firstname = ceo_without_title[m+1:]
print(salutation)
print(title)
print(firstname)
print(lastname)

My Five - stores five names and five numbers before being promoted for a number need input

For class I need to create a code that stores five names of your friends and five numbers in two separate arrays and then outputs the list of your five friends. The user would then be prompted for a number between 1 and 5, and the program will determine the person and the number to dial.
it should look something like -
1. Jack Black
2. Robert Downey Jr.
3. Chris Evens
4. Scarlett Johansson
5. Harry Potter
Please enter a number (1-5): *4*
Calling Scarlett Johansson at 416-568-8765
right now I have:
name = ["Paige"]
number = ["519-453-4839"]
#populate with a while loop
while True:
#add an element or q for quit
addname = input("Enter a name, or q to quit ").lower()
if addname == "q":
break
else:
theirnumber = input("Enter their number ")
#adds to the end of the list
name.append(addname)
number.append(theirnumber)
#when they break the loop
#print the lists side by side
print()
print("Name \t\t\t Number")
print("----------------------------------")
for x in range(len(name)):
print(f"{name[x]} \t\t\t {number[x]}")
#search for a gift and who gave it
searchItem = input("What name are you looking for? ")
if searchItem in name:
nameNumber = name.index(searchItem)
print(f"{name[nameNumber]} is the number {number[nameNumber]}")
else:
print("that is not a saved name, please enter a different name")
I'm not sure how to do it without asking for the numbers, if anyone has any ideas I would love to hear them.
#Mitzy33 - try to this and see if you follow, or have any other questions:
# two array for names, and the numbers
names = []
numbers = []
#populate with a while loop
while True:
# get the name and numbers:
name = input("Enter a name, or q to quit ")
if name == "q":
break
else:
number = input("Enter his/her number ")
#adds to the end of the list
names.append(name)
numbers.append(number)
#when they break the loop
#print the lists side by side
print(names)
print(numbers)
searchPerson = input("What name are you looking for? ").strip()
#print(searchPerson)
index = names.index(searchPerson)
print(f' {searchPerson} at {numbers[index]} ')
Output:
Enter a name, or q to quit John
Enter his/her number 9081234567
Enter a name, or q to quit Mary
Enter his/her number 2121234567
Enter a name, or q to quit Ben
Enter his/her number 8181234567
Enter a name, or q to quit Harry
Enter his/her number 2129891234
Enter a name, or q to quit q
['John', 'Mary', 'Ben', 'Harry']
['9081234567', '2121234567', '8181234567', '2129891234']
What name are you looking for? Harry
Harry at 2129891234
Instead of using two arrays you can do it using Python Dictionaries.
Use the name as the key and the number as the corresponding value.
peoples = {"Paige": "519-453-4839"}
You can add an item like that:
poeples["newName"] = "111-111-1111"
Then you can access the number like that:
peoples["Paige"]
So you can ask the name and return the number:
searchName = input("What name are you looking for? ")
print(f"{searchName} is the number {peoples[searchName]}")
If you have to use only arrays then you can find the index from the name:
searchName = input("What name are you looking for? ")
index = name.index(searchName)
print(f"{name[index]} is the number {number[index]}")

Name formatting in python with string splits

I have gotten mostly through this assignment but I am stuck as to obtain the proper outputs.
This assignment wishes that if the inputs are a full name, that the outputs are "last name, first initial. last initial. If the input was Stacy Estel Graham, the expected output should be Graham, S.E.
"Many documents use a specific format for a person's name. Write a program whose input is:
firstName middleName lastName
and whose output is:
lastName, firstInitial.middleInitial."
full_name = input()
mod_name = full_name.split(' ')
last_name= mod_name.pop(-1)
mod_name.join('.')
print(last_name)
print(mod_name)
I am completely lost on how to proceed.
You need to use '.'.join() to get the initials added.
To extract only the first char from the name, you can do mod_name[i][:1] where i is the index from 0 until last name - 1.
You can do something like this:
full_name = input('Enter your full name :')
mod_name = full_name.split(' ')
temp = '.'.join([mod_name[i][0] for i in range (0, len(mod_name) - 1)])
if temp == '':
print (mod_name[-1])
else:
print (mod_name[-1] + ', ' + temp + '.')
Here are some of the sample runs:
Enter your full name :Stacy Estel Sugar Graham
Graham, S.E.S.
Enter your full name :Stacy Estel Graham
Graham, S.E.
Enter your full name :Stacy Graham
Graham, S.
Enter your full name :Graham
Graham
Use:
def format_name(name):
names = name.split()
return f"{names[-1]}, {''.join([f'{i[0]}.' for i in names[:-1]])}"
Examples:
format_name('Stacy Estel Graham')
# > 'Graham, S.E.'
format_name('Randall McGrath')
# > 'McGrath, R.'
this code help you,but middle name is must for every person for creating your desire output
import re
s="Stacy Estel Graham"
words=s.split()
k=re.findall("[A-Z]",s)
p=words[-1]+","+k[0]+"."+k[1]
print(p)
Output:
Graham,S.E
Not with re :
full_name = input()
mod_name = full_name.split(' ')
last_name= mod_name.pop(-1)
first_inital = mod_name[0][0]
if len(mod_name) >= 2:
middle_inital = mod_name[1][0]
print(f'{last_name}, {first_inital}.{middle_inital}')
else:
print(f'{last_name}, {first_inital}.')
You can use string indexing and f' string format.
Input:
Hello World Python
Output:
Python, H.W.
full_name = input(')
mod_name = full_name.split(' ')
temp = '.'.join([mod_name[i][0] for i in range (0, len(mod_name) - 1)])
if temp == '':
print (mod_name[-1])
else:
print (mod_name[-1] + ', ' + temp + '.')

i want to delete the element even if user input is in small or Capital letter

nametoRemove = input("Enter the name you want to remove:")
print(nametoRemove)
name = ["Ramesh","Rakesh","Suresh"]
name.remove(nametoRemove)
print(name)
you can do it fith basic for loop and if statement:
nametoRemove = input("Enter the name you want to remove:")
print(nametoRemove)
name = ["Ramesh","Rakesh","Suresh"]
for item in name:
if item.lower() == nametoRemove.lower():
name.remove(item)
print(name)
output:
Enter the name you want to remove:ramesh
ramesh
['Rakesh', 'Suresh']

How to print values according to same lines from two different text files

I wanted the user to input a particular product name (which is saved in a file) and accordingly I wanted to print out price of the product (saved in a different file), but not able to do so.
I have just started out programming, so it's new to me.
def find_in_file(f) :
myfile = open("file1.txt")
products = myfile.read()
products = products.splitlines()
if f in products:
return "Product is in list"
else:
return "Product is not in list"
def printing_in_file(p) :
myprice = open("file2.txt")
price = myprice.read()
price = price.splitlines()
return price
if code in sec_code.values():
product = input("Enter product name: ")
print(printing_in_file(p))
I expected the price to be the output, but I am getting name 'p' is not defined.
This answer below works, but it is not complete, because you did not provide samples of your input files.
The code that you provided does not have a 'p' variable, so I replace it with the variable product. I created bool values for the returns in the function find_product (which was named find_in_file). If the inputted product name is an exact match (this will create problems) then a bool value of True is return. Next the code will call the function find_product_price (which was named printing_in_file) for the product name. I had to create files containing product names and prices, because you did not provide sample files as part of your question.
This code works, but it has limitation, because I do not know the exact format of your inputs files or sec_code values. With additional information this code can be improved or something new might replace some of it with something better.
Good luck with this coding problem.
def find_product(product_name) :
inventory_file = open('tmpFile.txt', 'r', encoding='utf-8')
products = inventory_file.read()
products = products.splitlines()
if product_name in products:
return True
else:
return False
def find_product_price(product_name) :
product_prices = open('tmpFile01.txt', 'r', encoding='utf-8')
prices = product_prices.read()
price = prices.splitlines()
if product_name in price:
return price
product = input("Enter product name: ")
product_search = find_product(product)
if product_search == True:
print ('The product is available.')
print(find_product_price(product))
# outputs
['cisco router $350']
elif product_search == False:
print (f'{product} are not available for purchase.')

Resources