Python Printing the String Result - python

import operator
def mkEntry(file1):
results = []
for line in file1:
lst = line.rstrip().split(",")
lst[2] = int(lst[2])
results.append(lst)
return print(sorted(results, key=operator.itemgetter(1,2)))
def main():
openFile = 'names/' + 'yob' + input("Enter the Year: ") + '.txt'
file1 = open(openFile)
mkEntry(file1)
main()
File:
Emily,F,25021
Emma,F,21595
Madison,F,20612
Olivia,F,16100
Joaquin,M,711
Maurice,M,711
Kade,M,701
Rodrigo,M,700
Tate,M,699
How do I print out the result looks like this:
1. Name (Gender): Numbers
Instead of ['name', 'gender', numbers]
I have trouble doing the string thing. It won't give me the good output. Any help?
Thanks

return print(sorted(results, key=operator.itemgetter(1,2))) isn't doing what you'd expect it to.
Because print() returns None, your function will return None. Get rid of the print statement (if you want to print the line, just put it before the return)
Then you can do in your main() function:
for person in mkEntry(file1):
print("1. {0} ({1}): {2}".format(*person))

Related

Why an extra none type str is returning?

Here is my code in Python for returning a string in capitalized :
import math
import os
import random
import re
import sys
def solve(s):
name = list(s.split())
for i in range(len(name)):
nparts = name[i].capitalize()
return print (nparts, end = " ")
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
s = input()
result = solve(s)
fptr.write(result + '\n')
fptr.close()
When I run only the function then the result is ok, but when I try to write the result in a file then I get the error below :
fptr.write(result + '\n')
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
By manually checking I found that when I am storing the result into the result variable it also gets an extra value "None". I have no idea why this is going on. Please help.
Your def solve(s): function doesn't return anything so by default it returns None
Fix it to:
def solve(s):
name = list(s.split())
return name
To capitalize each word a sentence :
split it
loop on it to capitalize each word
join them by space
import os
def solve(sentence):
return " ".join(word.capitalize() for word in sentence.split())
if __name__ == '__main__':
s = input("Give a sentence: ")
result = solve(s)
with open(os.environ['OUTPUT_PATH'], 'w') as fptr:
fptr.write(result + '\n')
When the programmer does not define functions to return anything, Python function by default return None. This is the thing that is happening in your program.
The function solve does not return anything and so returns None which gets stored in the variable result when the function is called
A change that you can make in your program is to return the name.
def solve(s):
name = list(s.split())
return name
Also, in your program, a return statement cannot be used within a for block.
Moreover, name is not defined in your main program. A tip to fix it would be to change the variable name from name to result in your for loop and place the for block after calling the function:
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
s = input()
name = solve(s)
for i in range(len(name)):
nparts = name[i].capitalize()
print (nparts, end = " ")
fptr.write(name[0] + '\n')
fptr.close()

How do i replace values of a list when found in the dictionary with its key? python

so im building a simple decoder tool currently it is able to decode texting short hand expressions, like lol, to its full phrase based off of values stored in a dictionary read in from a txt file. what i would like to do is reverse this process. I would like to take the phrase laugh out loud out of the string and replace it with its abbreviation, lol. I'm new to python so my knowledge is currently limited substantially. I do know a string in immutable so i know to convert the string to a list but my issue is how do i split the string and still keep the laugh out loud together so i can run it agaisnt the dictionary. here is my code minus the txt file any ideas or comments would be greatly appreciated.
class Decry:
def __init__(self):
self.dic_usr = 0
self.decrypted = "none"
self.encrypted = "none"
self.f = 0
self.list1 = []
self.list2 = []
self.list3 = []
self.dict1 = []
self.key1 = []
self.key2 = []
self.key3 = "none"
def __buildDiction__(self):
self.f = open("dict")
self.build_list = self.f.read().splitlines()
self.d_dict = {}
for i in self.build_list:
x = i.split(",")
self.d_dict[x[0]] = x[1]
return self.d_dict
def decoder(self, usr):
self.f = self.__buildDiction__()
self.list1 = usr.split(" ")
for i in self.list1:
if i in self.f:
self.list1[self.list1.index(i)] = self.f[i]
self.decrypted = " ". join(self.list1)
return self.decrypted
def dictionary(self):
self.f = self.__buildDiction__()
self.list2 = []
self.list3 = []
self.dict1 = []
for i in self.f:
self.list3.append(i)
self.list2.append(self.f[i])
for n, g in zip(self.list3, self.list2):
self.dict1.append(n)
self.dict1.append(g)
self.key1 = [self.dict1[i:i+2] for i in range(0, len(self.dict1), 2)]
self.key2 = [" ".join(x) for x in self.key1]
self.key3 = "\n".join(self.key2)
return self.key3
def main():
print("\nWelecome to quick decrypt!!!\n"
" /~~~~~~~~~~~~~~~~~~~~~~/")
print("\n\nUse the number you desire.\n"
"Proceed at your own risk:\n"
" 1. Decrypts\n"
" 2. Read dictionary\n"
" 3. Add definitions to dictionary\n"
" 4. Quit")
deco = Decry()
option = int(input())
if option == 1:
usr_input = str(input("Enter phrase to be decoded:\n"))
f = deco.decoder(usr_input)
print(f, "\n")
return main()
if option == 2:
f = deco.dictionary()
print(f, "\n")
return main()
if option == 3:
with open("dict", "a") as txt1:
txt1.write("\n" + str(input("Enter code followed by definition with a comma no space:\n")))
return main()
if __name__ == "__main__":
main()
my issue is how do i split the string and still keep the laugh out loud together so i can run it against the dictionary
Why split the string at all? Here is a very simple solution that I hope will illustrate an alternative way to solve this without needing to split the string:
phrases = {'lol': 'laugh out loud', 'tbd': 'to be decided', 'btw': 'by the way'}
userString = "by the way here is a simple solution laugh out loud"
for abbr, phrase in phrases.items():
userString = userString.replace(phrase, abbr)
print userString
Produces:
btw here is a simple solution lol
For larger strings you may want to consider looking at regular expressions or other more efficient techniques.
As an exercise you may want to think about how string.replace works - how would you implement that function?

How to pass a returned value into another function

I am trying to call the list I created in a sub-function, into another sub-function. Using parameters and call functions are my Achilles heel as it relates to python. I want to call the newList I created in the calculateZscore function, into mu globalChi function.
My current code:
import os
import math
'''
c:/Scripts/Lab2Data
NCSIDS_ObsExp.txt
chisquare.txt
output.txt
'''
def main():
directory = raw_input ("What is the working directory? ")
input_file = raw_input ("What is the name of the input file? ")
chiTable = raw_input ("What is the name of the chi-squared table? ")
outPut = raw_input ("What is the name of the output file? ")
path = os.path.join(directory,input_file)
path_1 = os.path.join(directory, chiTable)
path_2 = os.path.join(directory, outPut)
if __name__ == "__main__":
main()
def calculateZscore(inFileName, outFileName):
inputFile = open(inFileName,"r")
txtfile = open(outFileName, 'w')
for line in inputFile:
newList = line.strip().split(',')
obsExp = newList[-2:]
obsExp = list(map(int, obsExp))
obs = obsExp[0]
exp = obsExp[1]
zScore = (obs - exp) / math.sqrt(exp)
zScore = map(str, [zScore])
newList.extend(zScore)
txtfile = open(outFileName, 'w')
txtfile.writelines(newList)
inputFile.close() #close the files
txtfile.close()
return newList #return the list containing z scores
def globalChi(zscoreList):
print newList
You should read about the return statement. It is used to make a function return a result (the opposite of taking an argument), and cannot be used outside a function.
Here, you are doing the exact opposite.

Write list containing lists to file, and then reading it again

I'm quite new to python, and as a little project, I am trying to make an interactive program where I can store recipes, each recipe will be stored as a list of the format: [Name, Servings, [List of ingredients], [List of steps in method]]
The first function, that creates the list works (i.e. I have created and stored in the file [Scrambled eggs, 1, [2 eggs, milk.....], [Beat the eggs....]]
However when I then call the 'view_recipes' function, I get:
Name: [
Servings: '
Ingredients:
S
Method:
c
so it is clearly iterating over characters in the string.
Is it a problem with how I write my list to my file? (I've looked this up before and everyone says you just need to have f.write(str(list)) Else it must be a problem with the reading of a file: but how can I get python to import it as a list of lists?
My code so far:
import re
#Input file
f = open("bank.txt", "r+")
def add_recipe():
recipe = []
ingredients = []
method = []
#recipe = [name, servings, ingredients(as list), method(as list)]
recipe.append(raw_input("Please enter a name for the dish: "))
recipe.append(raw_input("How many servings does this recipe make? "))
print "Ingredients"
ans = True
while ans:
i = raw_input("Enter amount and ingredient name i.e. '250g Flour' or 'x' to continue: ")
if i.lower() == "x":
ans = False
else:
ans = False
ingredients.append(i)
ans = True
print "Ingredients entered: "
for ing in ingredients:
print ing
recipe.append(ingredients)
print "Method: "
ans2 = True
while ans2:
j = raw_input("Type next step or 'x' to end: ")
if j.lower() == "x":
ans2 = False
else:
ans2 = False
method.append(j)
ans2 = True
print "Method: "
for step in method:
print step
recipe.append(method)
print "Writing recipe information to file..."
print recipe
f.write(str(recipe))
f.write("\n")
def view_recipes():
for line in f:
print "Name: ", list(line)[0]
print "Servings: ", list(line)[1]
print "Ingredients: "
for k in list(line)[2]:
print k
print "Method: "
for l in list(line)[3]:
print l
I think your problem is that list(line) transform a string into a list of characters:
>>> l = "abc"
>>> list(l)
['a', 'b', 'c']
You should use something like pickle to read/write data to a file.
See for example this answer.
Edit: In order to be able to add more recipes to your file, you can
add all your recipes to some variable and read/write all at once
For instance something like
recipes = []
want_to_add_recipe = True
while want_to_add_recipe:
recipes.append(add_recipe())
ans = raw_input('more? ')
want_to_add_recipe = True if ans == 'y' else False
with open("Recipe.txt", "wb") as fo:
pickle.dump(recipe, fo)
And in add_recipe:
with open("Recipe.txt", "rb") as fo:
recipes = pickle.load(fo)
for name, serving, ingredients, method in recipes:
#print things
You will have to change add_recipe to return recipe.
add recipe to your file each time you call add_recipe:
read your file
load recipes if they exist
add your recipe to recipes
write the new recipes to the file
Also, check #jonrsharpe comment. You could easily use sqlite3 to avoid drawbacks of both my methods.

Python return function not working for me

I have the following code:
#gets the filename from the user
b= input("Please enter a file name to be opened: ")
a = (b+".txt")
#main data storage and other boolean options
data =[]
result1 =[]
on = True
#File reading in main body with try and except functionality.
try:
check = open(a, 'r')
line =check.readlines()
for items in line:
breakup= items.split()
number, salary, position, first, oname1, oname2, last = breakup
data.append(tuple([last, first + ' ' + oname1 + ' ' + oname2, number, position, salary]))
except IOError as e :
print("Failed to open", fileName)
#Employee creation function, takes the line and stores it in the correct position.
def employee_creation():
result = [((item[0] +", "+ item[1]).ljust(30), int(item[2]), item[3].ljust(15), int(item[4])) for item in data]
for items in result:
result1.append((items[0][0:30], format(items[1], "^5d"), items[2][0:15], "£"+format((items[3]),"<8d")))
return(result)
employee_creation()
print(result)
while on == True:
print("Please select what option you would like to use to search for employees:")
option = int(input("""
1 - Salary (X to X)
2 - Job Titlle
3 - Name, Payroll Number
:"""))
if option == 1:
start = input("What range would you like to start from: ")
end = input("What is the maximum range you would like :")
for items in result:
print(items[3])
if items[3]>start and items[3]<end:
print(items)
else:
print("No employees with this information can be found")
on= False
else:
on= False
However my def employee_creation() doesn't actually return result. I need it to make it a global variable so that I can use it to launch personal querys against the data.
Can anyone see why its not working?
No need to use the evil global variables. You forgot to store the result of your function to another variable.
def employee_creation():
result = [((item[0] +", "+ item[1]).ljust(30), int(item[2]), item[3].ljust(15), int(item[4])) for item in data]
for items in result:
result1.append((items[0][0:30], format(items[1], "^5d"), items[2][0:15], "£"+format((items[3]),"<8d")))
return result # no need for () here
result = employee_creation() # store the return value of your function
print(result)

Categories