How to receive a list of unknown length of strings - python

I'd like to receive a list of user aliases for the purpose of looking up an email. As of now, I can do this for only 1 input with the following code:
def Lookup(Dict_list):
user_alias = raw_input("Please enter User Alias: ")
data = []
for row in Dict_list:
#print "row test"
#print row
if user_alias in row.values():
print row
for row in Dict_list:
if user_alias == row['_cn6ca']:
email = row['_chk2m']
print email
return email
But I want to be able to have the user enter in an unknown amount of these aliases (probably no more than 10) and store the resulting emails that are looked up in a way that will allow for their placement in a .csv
I was thinking I could have the user enter a list [PaulW, RandomQ, SaraHu, etc...] or have the user enter all aliases until done, in which case they enter 'Done'
How can I alter this code (I'm guessing the raw_data command) to accomplish this?

This will accept input until it reaches an empty line (or whatever sentinel you define).
#! /usr/bin/python2.7
print 'Please enter one alias per line. Leave blank when finished.'
aliases = [alias for alias in iter (raw_input, '') ]
print (aliases)

You can ask the user to enter a list of aliases, separated by spaces, and then split the string:
In [15]: user_aliases = raw_input("Please enter User Aliases: ")
Please enter User Aliases: John Marry Harry
In [16]: for alias in user_aliases.split(): print alias
John
Marry
Harry
In [17]:
In case the user aliases can have spaces in them, ask them to use, say, a comma as a separator and split by that: user_aliases.split(',')

Related

Write a program that first takes in word pairs that consist of a name and a phone number (both strings), separated by a comma

I have the following prompt:
A contact list is a place where you can store a specific contact with other associated information such as a phone number, email address, birthday, etc. Write a program that first takes in word pairs that consist of a name and a phone number (both strings), separated by a comma. That list is followed by a name, and your program should output the phone number associated with that name. Assume the search name is always in the list.
Ex:
If the input is: Joe,123-5432 Linda,983-4123 Frank,867-5309 Frank the
output is: 867-5309
my code:
pn = str(input()).split()
search = str(input())
i=0
for i in range(len(on)):
if pn[i] == (search):
print([i+1])
The input is getting split into a name and number. When the code goes to check if the names are the same, it always returns false. I've tried using the re.split() method, but it didn't work.
You should split twice and second split char should be a comma s.split(",")
s = "Joe,123-5432 Linda,983-4123 Frank,867-5309"
for i in s.split():
temp = i.split(",");
print("name :", temp[0] , " number is :" , temp[1] )
Output
name : Joe number is : 123-5432
name : Linda number is : 983-4123
name : Frank number is : 867-5309
Try splitting around the comma when searching for the name:
pn = input().split()
search = input()
for i in pn:
val = i.split(',')
if val[0] == search:
print(val[1])
You need to have the following things in your program to meet the basic requirements
Infinite loop to enter contact info until user stop entering
List or Dictionary to hold entered info and for searching
The code can be like following
contacts = {}
while True:
info = input('Enter Contact Info or Leave empty to Stop Entering: ').split(',')
if len(info) > 1:
contacts[info[0]] = info[1]
else:
break
name = input('Enter name to search: ')
print(contacts[name])
Output is following
It seems like you're trying to store the data as an input, ask the user for a query (name of a person), and then respond with that person's phone number.
# Get the data
inputs = input("Enter the input. >>> ").split(sep=" ")
# Split the data into lists
for pos in range(len(inputs)):
inputs[pos] = inputs[pos].split(sep=",")
# Ask for a search query
query = input("Enter a name. >>> ")
# Check for the name in the first element of each item
for item in inputs:
if item[0] == query:
print(f"{query}'s phone number is {item[1]}.")
break
A sample data input, as called in line 2:
Enter the input. >>> John,12313123 Bob,8712731823
As of the search query line of the code, your inputs variable looks something like: [['John', '12313123'], ['Bob', '8712731823']]. The program will iterate through the items of inputs, where each item is a list of two strings, and then check if the first item of this sub-list matches the inputted query.
contact_list = input().split(sep=" ")
search_list = input()
def Convert(lst):
res_dct = {lst[i]: lst[i + 1] for i in range(0, len(lst), 2)}
return res_dct
contact_dict = Convert(contact_list)
print(contact_dict[search_list])

Advance on getting information from a menu

This is my entire code: https://github.com/samy-b/Assignment1/blob/main/addressbook
The main bit I am struggerling with is line 45. We have to create a function that will ask the user to enter the first letter of the surname of a person. Once the user has entered the letter then the program will display all of the attributes such firstname, lastname, address and phone number related to that letter. What can I use to make that happen?
Right after the user input the letter, make the program iterate through the keys of the info dictionary, using the subscription of [1] to get the Surname element of each list, and the subscription of [0] to get the first character of each surname:
elif user_input == 3:
firstletter = input("Please enter the first letter of their Surname")
for line in info:
if info[line][1][0] == firstletter:
print(info[line])
You can get the list of all surnames starting with what you typed:
list(filter(lambda u: u[1].startswith(firstletter), user_info))

How do you add users multiple inputs to a list?

In terms of using this:
names = [] # Here we define an empty list.
while True:
eingabe = input('Please enter a name: ')
if not eingabe:
break
names.append(eingabe)
print(eingabe)
How do you use it for multiple inputs?
Try this:
names = [] # Here we define an empty list.
flag = True
while flag:
eingabe = input('Please enter a name: ')
if not eingabe:
flag=False
names.append(eingabe)
print(eingabe)
So, until the flag not became False this while loop run continuously.
and if user does not entered any input value than it set the flag value False and loop will terminate.
If all you want is to convert multiple user inputs to a list, this will be the easiest way:
names = input('Please enter names (separated by space): ').split()
According to your question and given code above , it already takes multiple input from user but it seems that you are not printing them. If you want to get multiple input from user and add them to a empty list and print them out , then you've to change a bit more of your code.
names = []
while True:
eingabe = input('Please enter a name: ')
if not eingabe:
break
names.append(eingabe)
print(names)
or you can do this simply just using split() method -
names = input('Enter name like : "apple microsoft facebook ...": ').split()
print(names)
Please let me know whether it is or not.

How to check if the input has already been entered into a txt file

I have written code that creates a text file (if it doesn't exist) and asks you to input a name and an age to record peoples names and ages. I would like to add an elif into my code so that I can update peoples ages.
For example if a text file held the name Paul and their age was 46 and I typed in Paul when asked to input a name, I'd like it to just ask for an updated age.
Here is my attempt that simply doesn't work.
Code:
while True:
family=open("FamilyAges.txt",'a+')
familyR=open("FamilyAges.txt",'r')
line1= familyR.readlines(1)
name = input('Enter name of person : ')
if name == 'end':
break
elif name == line1:
print('test')
else:
age = input('Enter age of person : ')
family.write((name)+' '+(age)+'\n')
family.close()
Text File:
Paul 46
Sarah 46
The best solution is to read all the file, keep it in memory using a dict then update the dict every time you add a name.
When you decide to stop (input 'end') overwrite the file with the new values in the dict
The following solves your immediate problem with the code you posted, however for the goal you described you should think about: This code only checks the first line of your file but you want to check if the name is anywhere in the file.
readlines(1) returns a list with one element (the first line). So what you need is:
while True:
family=open("FamilyAges.txt",'a+')
familyR=open("FamilyAges.txt",'r')
line1= familyR.readlines(1)
name = input('Enter name of person : ')
if name == 'end':
break
elif name in line1[0]:
print('test')
else:
age = input('Enter age of person : ')
family.write((name)+' '+(age)+'\n')
family.close()
Note the line1[0] and the name in line1[0] (you need this because your line contains not only the name but additional text).
A bit longer then Joe's solution, but I like functions more. I did not correct your code, because certain parts were missing - rewriting seemed a better option keeping to stuff you did use.
After gianluca answer "what" to do I implemented an example of that for you.
I use the with open(...) as f: instead of your type of file reading as it automatically will close/flush/dispose of the filehandle when leaving the following block. Its the recommed way to operate with files. Dictionariesis a data structure for fast key/value access and better suited to your problem then simple strings.
See also reading-and-writing-files
Reading the whole file
input loop until done, modifying the dict
then (if needed) saving it.
Breaking up funcionality into funcitons is that have a limited scope and are easier to understand helps keep the code cleaner.
def readFile(fn):
"""Read the file given as by filename fn.
Expected format:
one key:value per line, key being a name, value a string as age.
Returns a dictionary of the parsed contents key:value if no
errors occure. Returs False on IOError or FileNotFoundError"""
try:
with open(fn,"r") as f:
lines = f.read().split("\n") # read all, split at linebreaks
print(lines) # debugging output
rv = {}
for l in lines: # parse all lines
item =l.split(":",2) # split each
if item is not None and len(item)==2: # must be 2 parts
rv[item[0]] = item[1] # put key/valu into dict
return rv # return dict
except IOError:
return False # error - return false
except FileNotFoundError:
pass # error - no file, thats ok
return {} # no file found, return empty dict
def saveFile(fn,famil):
"""Saves a dictionary famil as filename fn.
Produced format:
one key:value per line, key being a name, value a string as age.
Overwrites existing file of same name with new contents."""
with open(fn,"w+") as f:
for i in famil: # for all keys in dict
f.write(i + ":" + famil[i] + "\n") # write file
fileName = "FamilyAges.txt" # consistent filename
family = readFile(fileName) # read it
if not isinstance(family,dict): # check if no error, if error, print msg & quit
print("Error reading file")
else: # we got a dict
print(family) # print it
gotInput = False # remember for later if we need to save new data
while True: # loop until name input is "end"
name = input('Enter name of person : ') # input name
if name == 'end': # check break condition
break
else:
age = input('Enter age of person : ') # input age as string, no validation
family[name] = age # store in dictionary
gotInput = True # this will "alter" existing
# ages for existing names
if (gotInput): # if input happened, save data to file
saveFile(fileName, family)
print(family) # print dict before end
The steps:
if the file exists (could use try...except or os.path):
Create a dictionary of name: age pairs of people already in there
else:
Create an empty dictionary
begin a loop
input name
if name == "end" break out of loop
input age
set name entry in the dictionary to age (will override if not already set)
continue looping
open the file again, but in write ("w") mode so it is blanked
loop through each person in the dictionary (old and new)
write to the file their name and age (separated by a space) and then a new-line
Here's what that looks like:
try:
d = {n:a for n, a in (l.split() for l in open("FamilyAges.txt").readlines())}
except FileNotFoundError:
d = {}
while True:
name = input("name: ")
if name == "end":
break #will escape loop here, so no need for `elif`s
age = input("age: ") #no need to convert to an integer as noo calculations
d[name] = age
with open("FamilyAges.txt", "w") as f:
for person in d.items():
f.write(" ".join(person) + "\n")
And it works!
$ python t.py
name: bob
age: 23
name: cat
age: 98
name: end
$ cat FamilyAges.txt
bob 23
cat 98
$ python t.py
name: bob
age: 67
name: fish
age: 10
name: end
$ cat FamilyAges.txt
bob 67
cat 98
fish 10

How to match exact user input

I have below code in test.py file:
#!/usr/bin/python
import sys,re
def disfun():
a = str(raw_input('Enter your choice [PRIMARY|SECONDARY]: ')).upper().strip()
p = re.compile(r'\s.+a+.\s')
result = p.findall("+a+")
print result
disfun()
When I run this code, it gives a prompt for Enter your choice and if I give my choice as PRIMARY. I am getting only blank output:
[oracle#localhost oracle]$ ./test.py
Enter your choice [PRIMARY|SECONDARY]: PRIMARY
[]
Here I want to get the same output as I given in user input. Please help me on this.
Not sure what your goal is but I think you mean this?? Mind the quotes, 'a' is your user input. If you write "+a+" it will be literaly the string '+a+'
def disfun():
a = str(raw_input('Enter your choice [PRIMARY|SECONDARY]: ')).upper().strip()
p = re.compile(r'.*'+a+'.*') <-- this will match anything containing your user input
result = p.findall(a)
print result

Categories

Resources