Hello hopefully someone can steer me in the right direction.
I am trying to figure out how use def function to modify lines of text in a list according to user input. eg if user enters "a", it adds a line to the list, "d" = delete line and so on...
I have defined the functions and know what they have to do, here is some of it:
lineList = []
lines = ""
##Add Line
def addLine ():
while lines != "#":
lines = input ("Add a line: ")
lineList.append(lines)
for (i, item) in enumerate(lineList, start=1):
print(str(i)+":", item)
##Delete Line
def deleteLine ():
lineNum = int(input("Enter line: ") )
del lineList[(lineNum)]
for (i, item) in enumerate(lineList, start=1):
print(str(i)+":", item)
##Find and replace string
def findReplace ():
findString = input("Find string: ")
replaceString = input ("Replace with: ")
for n, i in enumerate(lineList):
if i == findString:
lineList[n] = replaceString
for (i, item) in enumerate(lineList, start=1):
print(str(i)+":", item)
So I am trying to find out: should the initial list be inside addLine () or outside it? Should I use addLine() to just append the list? Also how do the other functions access the list to make changes?
You can make the functions accept the current lineList as a parameter and return it back after changes. For example:
##Add Line
def addLine(lineList):
lines = ""
while lines != "#":
lines = input ("Add a line: ")
lineList.append(lines)
for (i, item) in enumerate(lineList, start=1):
print(str(i)+":", item)
return lineList
##Delete Line
def deleteLine(lineList):
lineNum = int(input("Enter line: "))
del lineList[(lineNum)]
for (i, item) in enumerate(lineList, start=1):
print(str(i)+":", item)
return lineList
##Find and replace string
def findReplace(lineList):
findString = input("Find string: ")
replaceString = input ("Replace with: ")
for n, i in enumerate(lineList):
if i == findString:
lineList[n] = replaceString
for (i, item) in enumerate(lineList, start=1):
print(str(i)+":", item)
return lineList
lineList = []
while True:
command = input("Enter command (a, d, f): ")
if command == "a":
lineList = addLine(lineList)
elif command == "d":
lineList = deleteLine(lineList)
elif command == "f":
lineList = findReplace(lineList)
From what i understood what u are trying to do u need to have the linelist variable outside the functions so it is a global variable and then u can access it from everywhere even inside functions. if u declare that variable inside the function add u will need to add at the beginning of the add function:
def addLine ():
global linelist
linelist = []
while lines != "#":
lines = input ("Add a line: ")
lineList.append(lines)
for (i, item) in enumerate(lineList, start=1):
print(str(i)+":", item)
this way the variable is global aswell, but it is easier to use it just outside the function.
hope this helps :D
It's better if you just make your functions take the list as function parameters. It's generally bad practice to use global variables, and you should avoid them whenever possible. That way, your functions can be self-contained and independant, which is a good design trait. So, just make it an argument instead.
Also, the following block of code is redundant in every function of yours. It'd be better if you just encapsulate it inside of a function too.
for (i, item) in enumerate(lineList, start=1):
print(str(i)+":", item)
For example:
def print_lines(line_list):
for (i, item) in enumerate(lineList, start=1):
print(str(i)+":", item)
This way, you don't have to worry about the for loop everytime, and can just have print_lines(line_list) in your functions instead.
Protip: Have a look at the PEP-8 Style Guide. This PEP will give you some insight on how you should style your code.
Hope the answer helped :)
Related
I want to pass a dictionary between two functions, but how to do this without using a global variable?
I'm trying to pass the dictionary that is in my "fileProcessing" function into the "swappingKandV_PrintingResults" function without having a global variable being modified.
dictionary = dict()
fileinputname = input("Please Input File Name: ")
try:
filehandling = open(fileinputname)
except:
print("Invalid Entry")
quit()
rawfile = filehandling.readlines()
def fileProcessing(rawfile):
for iteration in(range(len(rawfile))):
rawfile[iteration] = rawfile[iteration].lower()
for line in rawfile:
line.rstrip()
line.split()
for words in line:
letter = words.split()
for iteration in letter:
if iteration.isalpha() :
dictionary[iteration] = dictionary.get(iteration, 0) + 1
def swappingKandV_PrintingResults(dictionary):
finalresults = []
for (k,v) in dictionary.items():
newtuple = (v, k)
finalresults.append(newtuple)
finalresults = sorted(finalresults, reverse=True)
for iteration in finalresults:
print(iteration)
fileProcessing(rawfile)
swappingKandV_PrintingResults(dictionary)
By making the first function create and return the dictionary. Then pass that returned dictionary to the second function.
fileinputname = input("Please Input File Name: ")
try:
filehandling = open(fileinputname)
except:
print("Invalid Entry")
quit()
rawfile = filehandling.readlines()
def fileProcessing(rawfile):
dictionary = {}
for iteration in(range(len(rawfile))):
rawfile[iteration] = rawfile[iteration].lower()
for line in rawfile:
line.rstrip()
line.split()
for words in line:
letter = words.split()
for iteration in letter:
if iteration.isalpha() :
dictionary[iteration] = dictionary.get(iteration, 0) + 1
return dictionary
def swappingKandV_PrintingResults(dictionary):
finalresults = []
for (k,v) in dictionary.items():
newtuple = (v, k)
finalresults.append(newtuple)
finalresults = sorted(finalresults, reverse=True)
for iteration in finalresults:
print(iteration)
swappingKandV_PrintingResults(fileProcessing(rawfile))
From the way you phrased the question, it seems you have some confusion on how to work with passing arguments to functions and how to handle scope. I would suggest having at look at what a variable is in Python to begin with and then what passing it to a function means.
You can accomplish this task in 2 ways:
1. Nested Function Call :
If you want to necessarily call 2nd function after 1st, just write -
'swappingKandV_PrintingResults(dictionary)' as the ending line in the fileProcessing function.
2. Accepting Return from 1st and Passing as Argument to 2nd :
As insisted by #Reti43 too, just write -
'return dictionary' as the ending line in the fileProcessing function and replace your last 2 lines of code by -
Dict = fileProcessing(rawfile)
swappingKandV_PrintingResults(Dict)
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?
So, I'm trying to make something simple:
shopping_list = []
print("Enter 'done' to stop adding items.")
while True:
new_item = input("> ")
if new_item.lower() == "done":
break
shopping_list.append(new_item)
print("Here's your list:")
for item in shopping_list:
print(item)
Can I, instead of printing this, return the list to another file in order to display that file? I'm new to this and am not sure if that's possible (though everything is possible with code, right?). My goal is to get the list to display, and to be saved so I can access it anytime.
For starters, you'll need to put your code inside a function. Or else, you won't be able to "return" anything.
def foo():
....
return shopping_list
So, your code would be something like:
def foo():
while True:
new_item = input("> ")
if new_item.lower() == "done":
break
shopping_list.append(new_item)
return shopping_list
And, you'd call your function like this:
my_shopping_list = foo()
Once the function returns, my_shopping_list is a list of shopping items, you are free to do as you please.
Also notice I removed the print statements from your loop. Please feel free to add them in if you need them, but I assume that's what you didn't want.
Now, when you say file, I assumed you just meant to somewhere else inside the same program. But if you do indeed want to call this function from another python script, here's what you'll do:
A.py:
def foo():
... # entire function definition here
B.py
import A
my_shopping_list = A.foo()
Create two python scripts. The first one houses your foo function. The second one calls it.
Alternatively, if you want to print your shopping list to an actual file (taking your words literally here), you'd do:
foo():
...
with open('cart.txt', 'w') as f:
for i in shopping_list:
f.write(i + '\n')
This writes your items to a file.
If you mean that you want to run the list to a text file outside of your python script you can do the following:
outfile = open(file, "w")
CODE
outfile.write(shoppping_list)
outfile.close()
You can try this way :
def func():
shopping_list = []
print("Enter 'done' to stop adding items.")
while True:
new_item = input("> ")
if new_item.lower() == "done":
break
shopping_list.append(new_item)
return shopping_list
if __name__ == '__main__':
print("Here's your list:")
outfile = open('test.txt', "w")
shopping_list = func()
# outfile.write(shopping_list)
for item in shopping_list:
# print(item)
outfile.write(item + "\n")
outfile.close()
I have a starting file which has values on each line separated by a comma, like so:
hello,welcome
hi, howareyou
hola,comoestas
I want to take those words and put them into a dictionary so they are key/value pairs. Then i am trying to ask for a key and return the corresponding value. I believe i am close so any help would be appreciated. Also i am a beginner so simple code is best.
def CreateDictionary():
WordDictionary = open('file.csv', 'r')
for line in WordDictionary:
mylist = line.split(',')
return(mylist)
def main():
cd = CreateDictionary()
text=input('input text:')
for x in cd.values():
if x == text:
word=cd[x]
print(word)
main()
def makeDict(infilepath):
answer = {}
with open(infilepath) as infile:
for line in infile:
key,val = line.strip().split(',')
answer[key] = val
return answer
def main(infilepath):
cd = makeDict(infilepath)
key = input('input text: ')
if key in cd:
print(cd[key])
else:
print("'%s' is not a known word" %key)
Here's a way you could edit your solution to create a dictionary.
def CreateDictionary():
ret_dict = {}
with open('file.csv', 'r') as WordDictionary:
for line in WordDictionary:
parts = line.split(',')
ret_dict[parts[0]] = parts[1]
return ret_dict
def main():
cd = CreateDictionary()
text = raw_input('input text:')
word = cd[text]
print word
main()
A main issue with your approach is that you have return inside of a for loop. The function will return after the first loop iteration and will not continue beyond the first line of the file.
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))