Need help writing function ticker - python

I'm currently trying to write a function ticker() that will open a file read it and ask the user to input a company name. When the user inputs the company name it will return the ticker symbol of that company.
Also a data file is given, which is formatted in this way:
Name of Company #1
Ticker Symbol of Company #1
Name of Company #2
Ticker Symbol of Company #2
...
The view that I need is something like this:
ticker('test.txt')
Enter Company Name: YAHOO
Ticker: YHOO
My current code is:
def ticker(x):
d = {}
infile = open(x,'r')
content = infile.readlines()
for line in (x):
file = line.split('\n')
But now I'm completely lost as how to compute this.

I'm not sure what the format of the file you're reading in is, but the following code will read in the file and break it up into non-blank lines.
def ticker(filename):
lines = open(filename).read().split('\n')
lines = [x in lines if x]

Either change your fileformat, or try this:
ticker = {}
for company, ticker in (x):
ticker[company] = ticker
This will give you a dictionary, which can ba accessed in a manner like dictionary[key] and return its value. I am sure if you google for getting user input you can get this to work. Maybe apply a case conversion, so that the capitalization of the user input does not matter.
If this does not take you far enough consider trying harder/hiring a consultant or asking questions that show that you acctually put effort into it.

Below is a very raw and simple implementation, you can improve it.
def ticker(filename):
name = raw_input("Enter Company Name:")
f = open(filename, "r")
l = f.readline()
ticker = ''
while l:
if l.strip() == name:
ticker = f.readline().strip()
break
else:
l = f.readline()
if ticker:
print "Ticker: %s" % ticker
else:
print "Ticker not found!"
ticker("1.txt")

If you're sure about the format of your data file, you can use code bellow, But always remember that working with files without handling possible exceptions is not a good idea.
def ticker(filename):
with open(filename, 'r') as f:
lines = [line.strip() for line in f.readlines()]
return dict(zip(lines[::2], lines[1::2]))
data = ticker('test')
name = raw_input('Enter Company Name: ')
print 'Ticker:', data.get(name.strip(), 'Not Found!')

Related

Creating a search function in a list from a text file

everyone. I have a Python assignment that requires me to do the following:
Download this CSV fileLinks to an external site of female Oscar winners (https://docs.google.com/document/d/1Bq2T4m7FhWVXEJlD_UGti0zrIaoRCxDfRBVPOZq89bI/edit?usp=sharing) and open it into a text editor on your computer
Add a text file to your sandbox project named OscarWinnersFemales.txt
Copy and paste several lines from the original file into your sandbox file. Make sure that you include the header.
Write a Python program that does the following:
Open the file and store the file object in a variable
Read the entire contents line by line into a list and strip away the newline character at the end of each line
Using list slicing, print lines 4 through 7 of your file
Write code that will ask the user for an actress name and then search the list to see if it is in there. If it is it will display the record and if it is not it will display Sorry not found.
Close the file
Below is the code I currently have. I've already completed the first three bullet points but I can't figure out how to implement a search function into the list. Could anyone help clarify it for me? Thanks.
f = open('OscarsWinnersFemales.txt')
f = ([x.strip("\n") for x in f.readlines()])
print(f[3:7])
Here's what I tried already but it just keeps returning failure:
def search_func():
actress = input("Enter an actress name: ")
for x in f:
if actress in f:
print("success")
else:
print("failure")
search_func()
I hate it when people use complicated commands like ([x.strip("\n") for x in f.readlines()]) so ill just use multiple lines but you can do what you like.
f = open("OscarWinnersFemales.txt")
f = f.readlines()
f.close()
data = {} # will list the actors and the data as their values
for i, d in enumerate(data):
f[i] = d.strip("\n")
try:
index, year, age, name, movie = d.split(",")
except ValueError:
index, year, age, name, movie, movie2 = d.split(",")
movie += " and " + movie2
data[name] = f"{index}-> {year}-{age} | {movie}"
print(f[3:7])
def search_actr(name):
if name in data: print(data[name])
else: print("Actress does not exist in database. Remember to use captols and their full name")
I apologize if there are any errors, I decided not to download the file but everything I wrote is based off my knowledge and testing.
I have figured it out
file = open("OscarWinnersFemales.txt","r")
OscarWinnersFemales_List = []
for line in file:
stripped_line = line.strip()
OscarWinnersFemales_List.append(stripped_line)
file.close()
print(OscarWinnersFemales_List[3:7])
print()
actress_line = 0
name = input("Enter An Actress's Name: ")
for line in OscarWinnersFemales_List:
if name in line:
actress_line = line
break
if actress_line == 0:
print("Sorry, not found.")
else:
print()
print(actress_line)

Creating objects and adding them to a list by Reading CSV input in python

This is currently my code for reading through a CSV file, Creating a person object, and adding each person to a list. One line Example input: John,Langley,1,2,2,3,5
When i print(per) each time after creating a person object. My output is correct, but as soon as i add that person to the list i made, the numeric values AKA 'traits' for that person are all the same as the last persons traits in the CSV file.
For Example:
John,Langley,1,2,2,3,5 --(add to list)-->John,Langley,1,1,1,1,1
Isabel,Smith,3,2,4,4,0 --(add to list)-->Isabel,Smith,1,1,1,1,1
John,Doe,1,1,1,1,1 --(add to list)-->John,Doe,1,1,1,1,1
This is impacting me with continuing because i need the person objects' traits to be valid in order to perform analysis on them in the next couple methods. PLEASE IGNORE MY PRINT STATEMENTS. THEY WERE FOR MY DEBUGGING PURPOSES
def read_file(filename):
file = open(filename, "r", encoding='utf-8-sig')
Traits_dict = {}
pl = []
next(file)
for line in file:
line = line.rstrip('\n')
line = line.split(',')
first = str(line[0].strip())
last = str(line[1].strip())
w = line[2].strip()
hobby = line[3].strip()
social = line[4].strip()
eat = line[5].strip()
sleep = line[6].strip()
Traits_dict["Work"] = w
Traits_dict["Hobbies"] = hobby
Traits_dict["Socialize"] = social
Traits_dict["Eat"] = eat
Traits_dict["Sleep"] = sleep
per = Person(first, last, Traits_dict)
print(per)
pl.append(per)
print(pl[0])
print(pl[1])
print(pl[2])
print(pl[3])
print(pl[4])
return pl
All the Traits_dict = {} are the same to all object since you initiating the dict before the loop so it's giving each Person object the same dict reference in it.
You can put the Traits_dict = {} inside the loop that it will create each Person a new dict
for line in file:
Traits_dict = {}

Print Lines from .csv based off criteria inputted from user

I am new to python and am looking for guidance on the task I am working on.
I am importing a csv file that looks like the list below.
invoice_id,customer_first_name,customer_last_name,part_number,quantity,total
18031,Hank,Scorpio,367,1,2.63
54886,Max,Power,171,3,50.79
19714,Jonathan,Frink,179,2,7.93
19714,Jonathan,Frink,378,2,32.34
22268,Gil,Gunderson,165,2,47.15
87681,Lionel,Hutz,218,1,50.83
84508,Lurleen,Lumpkin,257,1,81.95
34018,Lionel,Hutz,112,3,88.88
34018,Lionel,Hutz,386,3,86.04
34018,Lionel,Hutz,216,1,53.54
66648,Patty,Bouvier,203,3,70.47
I only want to print each line if its based off the criteria inputted by the user. For example, if the user inputs lname and then inputs Hutz the following would be printed out.
87681,Lionel,Hutz,218,1,50.83
34018,Lionel,Hutz,112,3,88.88
34018,Lionel,Hutz,386,3,86.04
34018,Lionel,Hutz,216,1,53.54
4 records found.
This is what I have so far...
salesdatafile= None
while True:
salesdatafilename=input("Enter the name of the file:")
try:
salesdata= open(salesdatafilename, 'r')
break
except FileNotFoundError:
print("{0} was not found".format ( salesdatafilename ))
search=input("Do you want to search by invoice id or lname? Please type id or lname: ")
idsearch=salesdata.readline()
if search== 'id':
idnumber=print(int(input('Please enter Id to search: ')))
while idsearch != '':
if idsearch== idnumber:
print(idsearch)
else:
lname=print(input('Please enter your last name: '))
while idsearch != '':
if idsearch== lname:
print(idsearch)
All that is printing out is lname or id inputted by the user.
Python has a csv module built in that you should be utilizing. Check out the below example code:
import csv
salesdatafilename = r"path/to/file.txt"
data = csv.reader(open(salesdatafilename))
last_name_to_look_for = "Lionel"
for invoice_id, customer_first_name, customer_last_name, part_number, quantity, total in data:
if customer_last_name == last_name_to_look_for:
print(invoice_id, customer_first_name, customer_last_name, part_number, quantity, total)
In your code you are comparing the entire line to the idnumber or lname. Instead you might want to try something like
if lname in idsearch:
<do something>
this will check if the lname is in the line somewhere.
For performance, I will use a generator to read the lines so that my program doesn’t crash were this to be a bigger file. So I will yield each line in that file with a generator function. Since generators return iteratirs, I will then iterate and filter every line that does not contain my search value and return only those that contain my search value.

Multiple Word Search not Working Correctly (Python)

I am working on a project that requires me to be able to search for multiple keywords in a file. For example, if I had a file with 100 occurrences of the word "Tomato", 500 for the word "Bread", and 20 for "Pickle", I would want to be able to search the file for "Tomato" and "Bread" and get the number of times it occurs in the file. I was able to find people with the same issue/question, but for other languages on this site.
I a working program that allows me to search for the column name and tally how many times something shows up in that column, but I want to make something a bit more precise. Here is my code:
def start():
location = raw_input("What is the folder containing the data you like processed located? ")
#location = "C:/Code/Samples/Dates/2015-06-07/Large-Scale Data Parsing/Data Files"
if os.path.exists(location) == True: #Tests to see if user entered a valid path
file_extension = raw_input("What is the file type (.txt for example)? ")
search_for(location,file_extension)
else:
print "I'm sorry, but the file location you have entered does not exist. Please try again."
start()
def search_for(location,file_extension):
querylist = []
n = 5
while n == 5:
search_query = raw_input("What would you like to search for in each file? Use'Done' to indicate that you have finished your request. ")
#list = ["CD90-N5722-15C", "CD90-NB810-4C", "CP90-N2475-8", "CD90-VN530-22B"]
if search_query == "Done":
print "Your queries are:",querylist
print ""
content = os.listdir(location)
run(content,file_extension,location,querylist)
n = 0
else:
querylist.append(search_query)
continue
def run(content,file_extension,location,querylist):
for item in content:
if item.endswith(file_extension):
search(location,item,querylist)
quit()
def search(location,item,querylist):
with open(os.path.join(location,item), 'r') as f:
countlist = []
for search in querylist: #any search value after the first one is incorrectly reporting "0"
countsearch = 0
for line in f:
if search in line:
countsearch = countsearch + 1
countlist.append(search)
countlist.append(countsearch) #mechanism to update countsearch is not working for any value after the first
print item, countlist
start()
If I use that code, the last part (def search) is not working correctly. Any time I put a search in, any search after the first one I enter in returns "0", despite there being up to 500,000 occurrences of the search word in a file.
I was also wondering, since I have to index 5 files with 1,000,000 lines each, if there was a way I could write either an additional function or something to count how many times "Lettuce" occurs over all the files.
I cannot post the files here due to their size and content. Any help would be greatly appreciated.
Edit
I also have this piece of code here. If I use this, I get the correct count of each, but it would be much better to have a user be able to enter as many searches as they want:
def check_start():
#location = raw_input("What is the folder containing the data you like processed located? ")
location = "C:/Code/Samples/Dates/2015-06-07/Large-Scale Data Parsing/Data Files"
content = os.listdir(location)
for item in content:
if item.endswith("processed"):
countcol1 = 0
countcol2 = 0
countcol3 = 0
countcol4 = 0
#print os.path.join(currentdir,item)
with open(os.path.join(location,item), 'r') as f:
for line in f:
if "CD90-N5722-15C" in line:
countcol1 = countcol1 + 1
if "CD90-NB810-4C" in line:
countcol2 = countcol2 + 1
if "CP90-N2475-8" in line:
countcol3 = countcol3 + 1
if "CD90-VN530-22B" in line:
countcol4 = countcol4 + 1
print item, "CD90-N5722-15C", countcol1, "CD90-NB810-4C", countcol2, "CP90-N2475-8", countcol3, "CD90-VN530-22B", countcol4
You are trying to iterate over your file more than once. After the first time, the file pointer is at the end so subsequent searches will fail because there's nothing left to read.
If you add the line:
f.seek(0), this will reset the pointer before every read:
def search(location,item,querylist):
with open(os.path.join(location,item), 'r') as f:
countlist = []
for search in querylist: #any search value after the first one is incorrectly reporting "0"
countsearch = 0
for line in f:
if search in line:
countsearch = countsearch + 1
countlist.append(search)
countlist.append(countsearch) #mechanism to update countsearch is not working for any value after the first
f.seek(0)
print item, countlist
PS. I've guessed at the indentation... You really shouldn't use tabs.
I'm not sure I get your question completely, but how about something like this?
def check_start():
raw_search_terms = raw_input('Enter search terms seperated by a comma:')
search_term_list = raw_search_terms.split(',')
#location = raw_input("What is the folder containing the data you like processed located? ")
location = "C:/Code/Samples/Dates/2015-06-07/Large-Scale Data Parsing/Data Files"
content = os.listdir(location)
for item in content:
if item.endswith("processed"):
# create a dictionary of search terms with their counts (initialized to 0)
search_term_count_dict = dict(zip(search_term_list, [0 for s in search_term_list]))
for line in f:
for s in search_term_list:
if s in line:
search_term_count_dict[s] += 1
print item
for key, value in search_term_count_dict.iteritems() :
print key, value

ValueError when trying to add to dictionary in Python

So I have a file in this format
CountryCode CountryName
USA United States
What I want to do is make a dictionary with the code as the key, and the country name as the value.
I have a function which has the intent of doing that
def country(string):
'''reads the contents of a file into a string and closes it.'''
#open the file
countryDict = {}
fin = open(string, 'r')
for eachline in fin:
code, country = eachline.split()
countryDict[code] = country
print (countryDict)
return countryDict
However, when I try to run it, I get ValueError: too many values to unpack (expected 2).
Any reason why this code doesn't work? A similar program that I had that created user names using code like this worked.
Code for username program for reference, this works, why doesn't the above:
def main():
print ("This program creates a file of usernames from a")
print ("file of names.")
# get the file names
infileName = input("What file are the names in? ")
outfileName = input("What file should the usernames go in? ")
# open the files
infile = open(infileName, 'r')
outfile = open(outfileName, 'w')
# process each line of the input file
for line in infile:
# get the first and last names from line
first, last = line.split()
# create a username
uname = (first[0]+last[:7]).lower()
# write it to the output file
print(uname, file=outfile)
# close both files
infile.close()
outfile.close()
print("Usernames have been written to", outfileName)
if __name__ == '__main__':
main()
Think about when line is:
USA United States
When you split it, it would create:
['USA', 'United', 'States']
And when you go to do first, last = line.split(), it will try to put three values into two variables (hence the error).
To prevent this, you can split once:
>>> first, last = 'USA United States'.split(None, 1)
>>> first
'USA'
>>> last
'United States'
Another way using regex
def country(string):
fin = open(string, 'r')
pat = r'\s*([A-Za-z0-9]*)\s+([A-Za-z0-9\s]*?)\n'
tup = re.findall(pat, fin)
return dict(tup)

Categories

Resources