In the beginning of my program, i opened a file with f = open("foods.txt", "r+"). Later I called this method i created
def findFood(food):
foodRegex = re.compile(r'(?P<food>\S+)\s+\-.*')
for line in f.readlines():
print line
duplicateFound = re.search(foodRegex, line)
if duplicateFound.group('food') == food:
return duplicateFound
else:
return False
However I run the method again. But my program doesn't work the way I want it to. Specifically
def build_meal_plan():
number_of_items = int(raw_input("How many items would you like to add to your meal plan? "))
count = 0
while number_of_items > 0:
print count
food = raw_input("Enter in food name: ")
print food
if findFood(food):
servings = int(raw_input("Number of servings: "))
else:
print "Food not found! Try again? (y/n): ",
choice = raw_input()
if choice == 'y' or choice == "yes":
number_of_items += 1
else:
return
However during the 2nd run of my findFood method I cannot locate an item i know exists within the .txt file. I am not sure why I cannot find the same item I found in the text file during the first run. My assumption is that you can only go through a txt file once.
Once you call f.readlines(), you are at the end of the file. To return to the start, so you can go through it again, call f.seek(0):
def findFood(food):
foodRegex = re.compile(r'(?P<food>\S+)\s+\-.*')
for line in f.readlines():
...
f.seek(0)
Alternatively, you can import the contents of the file to a list:
def import_file(filename):
with open(filename) as f:
content = [line.strip() for line in f]
return content
And use that instead of referring back to the file.
def findFood(food, data):
foodRegex = re.compile(r'(?P<food>\S+)\s+\-.*')
for line in data:
...
Then you don't need to worry about returning to the start.
Related
I want to call a function using a user input. A user will be asked to choose from n = which will call a function that will create a new line and d which will call another function that will delete a line from the user input. And if the user input is not in the choices it will go back to the choices.
And I need to create a function using 'del' keyword in order to delete the line. But i don't have any idea how to do that.
def add(n):
lines = list()
add_line = input('Add a line: ')
while add_line != '#':
lines.append(add_line)
add_line = input('Add a line: ')
for line in lines:
print(lines.index(line) +1, end = '')
print(":", line)
def delete(d):
def main():
choice= input ("Command n, d: ")
for a in choice:
add(n)
main()
my output should look like this:
Command n, d : n
Add a line: It is a lovely morning
Add a line: #
1: It is a lovely morning
Command n, d: d
Line number: 3
1: It is a lovely morning
2: for reading a book
You need to make lines global or pass it to the delete function.
lines = list() # move this out of add
def delete():
global lines
line_no = input('line number to delete: ')
del lines[int(line_no) - 1]
def main():
choice = input ("Command n, d: ")
if "a" in choice:
add()
elif "d" in choice:
delete()
main()
This code is meant to pick an artist from internal file (text file), read it and pick randomly from the internal file the artist (that are in the text file in array style, e.g., "carrot apple banana"), therefore I added .txt to the chosen artist so the program will open artist's file with songs and pick a random song.
import random
loop = False
counter = 0
points = 0
max_level = 10
while loop == False:
for lines in open("pick.txt").readlines():
art = lines.split()
artist = random.choice(art)
for i in open((artist) + ".txt"):
song = i.split()
song_name = random.choice(song)
print("the song begins with :" , song_name , "this song is by :" , artist)
answer = input("Enter full name of the song : ")
if answer == song_name:
points = points +3
print("correct")
counter = counter +1
print(counter)
elif answer != song_name:
print("WRONG !!! \n try again")
dec = input("Please enter the full name of the song :")
if dec == song_name:
points = points +2
print("correct")
counter = counter +1
print(counter)
elif dec != song_name:
print("smh \n WRONG")
counter = counter +1
print(counter)
elif counter >= max_level:
print("The End")
quit()
else:
print("error")
input()
Afterwards when I run the code in python shell, there is a random chance that I get this error, either straight away or later on:
raise IndexError('Cannot choose from an empty sequence') from None
IndexError: Cannot choose from an empty sequence
That error is from the random module by the looks of it. This is probably when you’re reading the file and there is a line that is blank.
A cause is usually the last line of the file which is often a blank newline/EOF.
Just add a check when reading your file(s):
for line in open(artist + '.txt', 'r'):
if line.strip():
song = line.strip().split()
song_name = random.choice(song)
An empty line will have a ‘truthiness’ value of 0 or False so a line with content returnsTrue.
Your error probably arises from an empty line in one of your text-files.
I was able to duplicate your error with your exact code and the following text-files:
pick.txt with only the word adele,
and adele.txt with hello-from-the-other-side and two new lines.
You can test this in prelude:
>>> for i in open("adele.txt"):
... song = i.split()
...
>>> song
[]
On another note, you seem to be iterating throughout the lines in a textfile before you do anything with the data in the lines. That can't possibly make sense. I would advice you to add things in a list as you go, and then select from this list instead.
import sys
import pickle
import string
def Menu():
print ("***********MENU************")
print ("0. Quit")
print ("1. Read text file")
print ("2. Display counts")
print ("3. Display statistics of word lengths")
print ("4. Print statistics to file")
def readFile():
while True:
fileName = input("Please enter a file name: ")
if (fileName.lower().endswith(".txt")):
break
else:
print("That was an incorrect file name. Please try again.")
continue
return fileName
THE_FILE = ""
myDictionary = 0
def showCounts(fileName):
numCount = 0
dotCount = 0
commaCount = 0
lineCount = 0
wordCount = 0
with open(fileName, 'r') as f:
for line in f:
wordCount+=len(line.split())
lineCount+=1
for char in line:
if char.isdigit() == True:
numCount+=1
elif char == '.':
dotCount+=1
elif char == ',':
commaCount+=1
print("Number count: " + str(numCount))
print("Comma count: " + str(commaCount))
print("Dot count: " + str(dotCount))
print("Line count: " + str(lineCount))
print("Word count: " + str(wordCount))
def showStats(fileName):
temp1 = []
temp2 = []
lengths = []
myWords = []
keys = []
values = []
count = 0
with open(fileName, 'r') as f:
for line in f:
words = line.split()
for word in words:
temp2.append(word)
temp1.append(len(word))
for x in temp1:
if x not in lengths:
lengths.append(x)
lengths.sort()
dictionaryStats = {}
for x in lengths:
dictionaryStats[x] = []
for x in lengths:
for word in temp2:
if len(word) == x:
dictionaryStats[x].append(word)
for key in dictionaryStats:
print("Key = " + str(key) + " Total number of words with " + str(key) + " characters = " + str(len(dictionaryStats[key])))
return dictionaryStats
def printStats(aDictionary):
aFile = open("statsWords.dat", 'w')
for key in aDictionary:
aFile.write(str(key) + " : " + str(aDictionary[key]) + "\n")
aFile.close()
choice = -1
while choice !=0:
Menu()
choice = (int(input("Please choose 1-4 to perform function. Press 0 to exit the program. Thank you. \n")))
if choice == 0:
print ("Exit program. Thank you.")
sys.exit
elif choice == 1:
THE_FILE = readFile()
elif choice == 2:
showCounts(THE_FILE)
elif choice == 3:
showStats(THE_FILE)
elif choice == 4:
printStats(myDictionary)
else:
print ("Error.")
I'm trying to open a file, have it display the statistics of the word lengths, and then have it make a new file with the statistics of the word lengths. I can read the file and have it display the statistics, but when I print the statistics to file I get an error - "int" object is not iterable. Any ideas? Thanks guys!
Error:
Traceback (most recent call last):
File "hw4_ThomasConnor.py", line 111, in <module>
printStats(myDictionary)
File "hw4_ThomasConnor.py", line 92, in printStats
for key in aDictionary:
TypeError: 'int' object is not iterable
The problem is that you set myDictionary to 0 at the top of your program, and then are sending it to your file writing function here printStats(myDictionary).
In this function you have this line for key in aDictionary, and since you passed in 0, this is effectively for key in 0 which is where the error comes from.
You need to send the result of the showStats function to your printStats function.
As this is looking like homework, I will leave it at that for now.
Sorry I am confused. in the showStats function I have to somehow say
"send results to printStats function" and then in the printStats
function I have to call the results? How would I do that exactly?
The printStats function is expecting a dictionary to print. This dictionary is generated by the showStats function (in fact, it returns this dictionary).
So you need to send the result of the showStats function to the printStats function.
To save the return value of a method, you can assign it on the LHS (left hand side) of the call expression, like this:
>>> def foo(bar):
... return bar*2
...
>>> def print_results(result):
... print('The result was: {}'.format(result))
...
>>> result = foo(2) # Save the returned value
Since result is just like any other name in Python, you can pass it to any other function:
>>> print_results(result)
The result was: 4
If we don't want to store the result of the function, and just want to send it to another function, then we can use this syntax:
>>> print_results(foo(2))
The result was: 4
You need to do something similar in your main loop where you execute the functions.
Since the dictionary you want to print is returned by the showStats function, you must call the showStats function first before calling the printStats function. This poses a problem if your user selects 4 before selecting 3 - make sure you find out a work around for this. A simple work around would be to prompt the user to calculate the stats by selecting 3 before selecting 4. Try to think of another way to get around this problem.
Here:
THE_FILE = ""
myDictionary = 0
you set integer to myDictionary.
and later you do:
printStats(myDictionary)
and as you try to interate over keys of dictionary inside, you fail.
I have a program that saves a file that you can write values to. What I am trying to do is use the saved files to calculate my mean/median/mode and to be able to delete values. functions. I am able to add values to the file through the open("filename","a")...but how do I make it so that I am able to import the file values to calculate my other functions?
Sorry its so long, but if anyone can help I would really appreciate it, I am new to figuring out File IO a stuff.
filename = input("What do you want to name your file? Be sure to include .txt after the filename!:")
def main(filename):
print("Now what would you like to do?")
print("--------------------------------------------------------------------------------")
print("Press 1 if you would like to ADD a Value to your list")
print("Press 2 if you would like to DELETE a Value from your list according to its value")
print("Press 3 if you would like to DELETE a Value from your list according to its location")
print("Press 4 if you would like to DISPLAY your List")
print("Press 5 if you would like to COMPUTE MEAN for your list")
print("Press 6 if you would like to COMPUTE MEDIAN for you list")
print("Press 7 if you would like to COMPUTE MIDPOINT for you list")
print("Press 8 if you would like to COMPUTE MODE(S) for your list")
print("Press 9 if you would like to COMPUTE STANDARD DEVIATION for your list")
print("Press 10 if you would like to READ values from a FILE you have made")
print("Press 0 if you would like to EXIT")
print()
execute = int(input("which action would you like to do next?"))
if execute == 1:
add_Values(filename)
if execute == 2:
remove_Value_List(filename)
if execute == 3:
del_Value_Location(filename)
if execute == 4:
read_file(filename)
if execute == 5:
computing_Mean(filename)
if execute == 6:
computing_Median(filename)
if execute == 7:
computing_Midpoint(filename)
if execute == 8:
computing_Modes(filename)
if execute == 9:
computing_Standard_Dev(filename)
if execute == 10:
read_file(filename)
if execute == 0:
print()
print("That's too bad I was having so much fun...but okay...bye!")
if execute >= 12:
print("Sorry but that is not one of the options")
if execute <= -1:
print("Sorry but that is not one of the options")
def add_Values(filename):
fout = open(filename,"a")
again = 'y'
while again == 'y':
fout.write(input("Enter a number you want to write to the file:")+"\n")
print("Do you want to add another number?")
again = input("y = yes, anything else = no:")
fout.close()
print("The numbers have been saved to the file")
main(filename)
def remove_Value_List(filename):
fout = open(filename, "r")
fout.readlines()
remove = "y"
while remove == "y":
print()
print("Here is your list:")
add_Values(filename)
number_list = float(input("Which value should I remove?"))
try:
values.remove(number_list)
print("Here is the revised list:")
print()
print()
except ValueError:
print("That item is not found in the list.")
number_list = float(input("which value should I remove?"))
remove = input("Would you like to remove a value? y = yes, amything else = no:")
fout.close()
print()
main(filename)
def del_Value_Location(filename):
remove = "y"
fout = open(filename,"r")
fout.readlines()
while remove == "y":
print()
print("Here is your list:")
add_Values(filename)
number_list = int(input("Which position should I remove?"))
try:
del values[number_list]
print("Here is the revised list:")
read_file_one(filename)
print()
except ValueError:
print("That item is not found in the list.")
number_list = float(input("which value should I remove?"))
remove = input("Would you like to remove a value? y = yes, amything else = no:")
fout.close()
print()
main(filename)
def computing_Mean(filename):
with open(filename,"r") as fout:
summ = 0
cnt = 0
for line in fout.readlines():
cnt += 1
summ += float(line.strip())
print ("Mean value is:" (summ/cnt))
def computing_Median(filename):
fin = open(filename,"r")
fin.readlines()
ordered = sorted(filename)
length = len(filename)
print("The median of this list is:")
print(float((ordered[length//2] + ordered[-(length+1)//2]))/2)
main(filename)
def computing_Midpoint(filename):
with open(filename,"r") as fout:
filename.sort(key=int)
minNum = min(float(filename))
maxNum = max(float(filename))
print("The midpoint of this list is:")
print((minNum + maxNum) / 2)
main(filename)
def computing_Modes(filename):
from collections import Counter
data = Counter(filename)
print("The Mode(s) of this list is/are:")
print(data.most_common(1))
main(filename)
def computing_Standard_Dev(filename):
mean = sum(filename)/len(filename)
for i in values:
total = 0
newDev = i - mean
squared = newDev**2
total = (total + squared)
divider = (total/(len(values)-1))
standardDev = divider**.5
print("The standard deviation is:")
print(standardDev)
main(filename)
def read_file(filename):
fin = open(filename, 'r')
L = fin.readlines()
for ix in range(len(L)):
L[ix]=L[ix].strip()
while "" in L:
L.remove("")
for ix in range(len(L)):
L[ix]=float(L[ix])
fin.close()
print(L)
main(filename)
main(filename)
There are lots of errors in your code which are very similar to each other so I will explain only one of those similar ones and you should fix others by examining fixed one.
For startes you are opening a file named filename. Using quotes around it makes it a string. You should use it like this:
def add_Values(filename):
fout = open(filename,"w")
But using with statement to open files is much more better because file is closed automatically even if exception is raised.
def add_Values(filename):
with open(filename) as fout:
#do smth
There is no file to work with in def del_Value_Location(filename): and some others. You should open your file in those as well.
To make calculations you need read your data from your file. Which can be achieved by using file.readlines()
def computing_Mean(filename):
with open(filename,"r") as fout:
summ = 0
cnt = 0
for line in fout.readlines():
cnt += 1
summ += int(line.strip())
print ("Mean value is: %.1f" % (summ/cnt))
If you want to change how many digits you want to see, you should change %.1f part.
With this you should fix your other computations by yourself.
About menu, you can do something like this to make it appear again without using a second function.
filename = input("What do you want to name your file? Be sure to include .txt after the filename!:")
#exclude this filename in main and use it as `main`s argument.
def main(filename):
print("Now what would you like to do?")
Ofcoure after this, you should change all main_two()s to main(filename).
I am trying to add a value to a list from a file, and then be able to add the values from the file to the list.
This is what I have:
L = []
def readFile(L):
ui = input("Please enter your file name:")
r = open(ui, 'r')
files = r.readlines()
for line in files:
return float(line)
L.append(line)
r.close()
def fileAddValue(L):
ui = input("Please enter your file name:")
val = float(input("Enter the value you would like to add to the list: "))
r = open(ui, 'a')
file = r.write(str(val) + '\n')
for ix in r:
x = float(ix)
L.append(x)
L.sort()
r.close()
You have a few problems...
First, when you open a file you need to use with, this will handle closing your file for you.
Now, when you read each line in turn you are returning the first one. That returns from the whole function so is not what you want. I take it you want to append each item onto your list.
Also, your functions are better made generic. Pass in the filename and the data. Get them outside the function for more flexibility.
It is not clear what you want to do here. I have assumed you want to specify values to add to a list which is persisted in a file. There are better ways to do this. This is my attempt based on your original code.
def readFile(ui):
L = []
with open(ui, 'r') as f:
for line in f.readlines():
L.append(float(line))
return sorted(L)
def fileAddValue(ui, val):
with open(ui, 'a') as f:
f.write(str(val) + '\n')
ui = raw_input("Please enter your file name:")
L = readFile(ui)
print('original file:')
print(L)
val = float(raw_input("Enter the value you would like to add to the list: "))
fileAddValue(ui, val)
L = readFile(ui)
print('updated file:')
print(L)
Do you need something like that?
L = []
def readFile():
ui = input("Please enter your file name:")
r = open(ui, 'r')
files = r.readlines()
for line in files:
value = float(line)
L.append(value)
r.close()
def fileAddValue():
ui = input("Please enter your file name:")
val = float(input("Enter the value you would like to add to the list: "))
r = open(ui, 'a+')
r.write(str(val) + '\n')
for ix in r:
x = float(ix)
L.append(x)
L.append(val)
L.sort()
r.close()
if __name__ == '__main__':
readFile()
fileAddValue()
print(L)
While it's non-pytonic (tried to not touch your code unless necessary), it works if I got your question right.
Indenting code is important in Python and returning from a function guarantees that code after return will never run. If you want a function that "returns" several values so you can iterate over that "function" with for, use yield instead of return.