Python 2.7.5 and OSX 10.8 here
I'm trying to plot some datas I get from a file.
I'm trying to code a function where the user is able to plot from the point he wants, and have come to this part of code :
firstPoint = raw_input("1st point to be displayed is n° : ")
tbdata3 = hdulist[3].data
print(hdulist[3].header['TTYPE24'])
print tbdata3.field('DDL_FT_OPL')
print(hdulist[3].header['TTYPE23'])
print tbdata3.field('DDL_SC_OPL')
dataFT=tbdata3.field('DDL_FT_OPL')
plt.subplot(211)
plot(dataFT[firstPoint:400,:])
dataSC=tbdata3.field('DDL_SC_OPL')
plt.subplot(212)
plot(dataSC[firstPoint:400,:])
show()
I get this error :
Traceback (most recent call last):
File "/Users/geoffroysarrazin/Desktop/stage_observatoire/testEkki.py", line 52, in essai
plot(dataFT[firstPoint:400,:])
IndexError: invalid slice
And it seems weird to me, cause I got this with
firstPoint=10
and just before, I had a constant value instead of this input from the user, which was equal to 200 (or whatever <400) and it worked...
Simple - you're not converting your input!
firstPoint = int(raw_input("1st point to be displayed is n° : "))
You can add some exception handling to re-prompt the user if he doesn't provide a number, if you so wish.
Related
New to python programming,While I was analysing spotify Datasets I got this error.
What I was doing was Plot a Line Graph to Show the Duration of the Songs for Each Year.
Any idea how do i fix this?
enter image description here
sns.displot(years,discrete=True,aspect=2,heights=5,kind="hist").set(title="Number of songs per year")
NameError Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_12628\3904715389.py in
----> 1 sns.displot(years,discrete=True,aspect=2,heights=5,kind="hist").set(title="Number of songs per year")
NameError: name 'years' is not defined
This is the Sample spotify datasets
enter image description here
I expecting solution for the Error.
the data years which you are trying to visualize through distplot may not be defined. Make sure to store in the variable first like , years = Your_Sample_spotify_data["year"] and than you can defined it as the first argument of distplot().
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I'm currently trying to populate a SQL database (for an assignment) through Python. I have created a function to help me do that.
When I run the function, however, I receive a 'List index out of range" Index error. I would appreciate all and any help!
I have tried reverting to some old code, but it doesn't help with the current problem.
As I understand that there is apparently no "field[1]" (otherwise I wouldn't be receiving this error) I have tried printing each step of my function as it occurs... only to discover that I can, in fact, print the elusive value, but still receive an error about that line?
I have included all the code I believe to be relevant, however, if you think I must be missing something, feel free to contact me. Thank you very much!
def populateStudentTable(textFile,targetTable):
connection = sqlite3.connect(dbName)
cursor = connection.cursor()
numRecs = 0
dataRecs = []
textRec = textFile.readline()
while textRec != "":
numRecs += 1
field = textRec.split(", ")
print(field)
print(field[0])
print(field[1])
textRec = textFile.readline()
When I run the program, it prints the second item in the list: field[1]
But then after that, it gives me an error...
['VENNGEOR', 'Georgia', 'Venna', '12', 'Maths', '8596746234']
VENNGEOR
Georgia
This is the error I receive:
Traceback (most recent call last):
File "h:\Digital Solutions\VS Code\Dev.py", line 22, in <module>
numRecs = populateStudentTable(textFile,"tblMentor")
File "h:\Digital Solutions\VS Code\Dev.py", line 14, in
populateStudentTable:print(field[1])
IndexError: list index out of range
After reading some comments and doing some more debugging of my own, I discovered that "buran" was correct. I had simply left some empty lines and was trying to run a loop on an empty line.
One line in textFile did not contain the number of , characters you expect. When you do field = textRec.split(", ") then resulting field might not have 3 elements as you expect if there was less than two , in the line.
Examine the content of your file or simply instead of printing elements of field print field itself. This will make it easier for you to understand where you got this wrong.
Also note you are splitting by ", " (not ","), so be aware of situations like this may also result in your error:
>>> foo = "a,b,c, d"
>>> foo.split(", ")
['a,b,c', 'd']
I am facing a difficulty in parsing the population count and appending it to a list
from bs4 import *
import requests
def getPopulation(name):
url="http://www.worldometers.info/world-population/"+name+"-population/"
data=requests.get(url)
soup=BeautifulSoup(data.text,"html.parser")
#print(soup.prettify())
x=soup.find_all('div',{"class":"col-md-8 country-pop-description"})
y=x[0].find_all('strong')
result=y[1].text
return result
def main():
no=input("Enter the number of countries : ")
Map=[]
for i in range(0,int(no)):
country=input("Enter country : ")
res=getPopulation(country)
Map.append(res)
print(Map)
if __name__ == "__main__":
main()
The function works fine if i run it separately by passing a country name such as "india" as a parameter but shows an error when i compile it in this program.I am a beginner in python so sorry for the silly mistakes if any present.
Traceback (most recent call last):
File "C:/Users/Latheesh/AppData/Local/Programs/Python/Python36/Population Graph.py", line 24, in <module>
main()
File "C:/Users/Latheesh/AppData/Local/Programs/Python/Python36/Population Graph.py", line 19, in main
res=getPopulation(country)
File "C:/Users/Latheesh/AppData/Local/Programs/Python/Python36/Population Graph.py", line 10, in getPopulation
y=x[0].find_all('strong')
IndexError: list index out of range
I just ran your code for the sample cases (india and china) and ran into no issue. The reason you'd get the indexerror is if there are no results for find_all, for which the result would be [] (so there is no 0th element).
To fix your code you need a "catch" to confirm there are results. Here's a basic way to do that:
def getPopulation(name):
...
x=soup.find_all('div',{"class":"col-md-8 country-pop-description"})
if x:
y=x[0].find_all('strong')
result=y[1].text
else:
result = "No results founds."
return result
A cleaner way to write that, eliminating the unnecessary holder variables (e.g. y) and using a ternary operator:
def getPopulation(name):
...
x=soup.find_all('div',{"class":"col-md-8 country-pop-description"})
return x[0].find_all('strong')[1].text if x else "No results founds."
A few other notes about your code:
It's best to use returns for all of your functions. For main(), instead of using print(Map), you should use return Map
Style convention in Python calls for variable names to be lowercase (e.g. Map should be map) and there should be a space before your return line (as in the shortened getPopulation() above. I suggest reviewing PEP 8 to learn more about style norms / making code easier to read.
For url it's better practice to use string formatting to insert your variables. For example, "http://www.worldometers.info/world-population/{}-population/".format(name)
I have code like this:
from datetime import datetime
from tabulate import tabulate
def search_projection_date():
projections = open('projections.txt','r').readlines()
date = input("Input projection date: ")
try:
date = date.strptime(date, "%d.%m.%Y.")
except:
print("Date input error!")
#search_projection_date()
for i in projections:
projections = i.strip("\n").split("|")
if date == projections[2]:
table = [['Code:',projections[0]],['Hall:',projections[1]],['Date:',projections[2]],['Start time:',projections[3]],['End time:', projections[4]],['Day(s):', projections[5]], ['Movie:', projections[6]], ['Price:', projections[7]]]
print (tabulate(table))
#break
else:
print("No projection on that date")
And text file like this:
0001|AAA|17.12.2017.|20:30|21:00|sunday|For a few dolars more|150
0002|BBB|17.12.2017.|19:30|21:15|saturday|March on the Drina|300
0003|GGG|19.12.2017.|18:00|19:00|tuesday|A fistful of Dolars|500
0004|GGG|16.12.2017.|21:15|00:00|sunday|The Good, the Bad and the Ugly|350
I try to search movie projections by date...
If there is a projection on the entered date it will find it and print the list, but before printing that list it will always print "Date input error" and after that list "No projection on that date". (if I put break in if statement it will print only the first found projection on entered day, withouth else statement, obvious)
Questions: How to print ONLY list of projections without "date input error" if date is correctly input.
How to print only "No projection on that date" if date is correct but there is no projection and how to ask user for input that until puts it correctly? In this way with recursion it will always throw exception and recursion search_projection_date() function.
There are a whole bunch of major problems with your code. As it happens, they showcase why some general advice we hear so often is actually good advice.
The line date = input("Input projection date: ") creates a string named date. input always returns a string. Strings in Python do not have a method called strptime. Which brings us to issue #2:
You should not catch generic exceptions. You were probably looking to trap a TypeError or ValueError in the except clause. However, you are getting an error that says AttributeError: 'str' object has no attribute 'strptime'. This is because you can't call methods that you want to exist but don't. Your except line should probably read something like except ValueError:.
Your except clause does nothing useful (beyond the problems listed above). If the string is not formatted correctly, you print a message but continue anyway. You probably want to use raise in the except clause to propagate the exception further. Luckily for you, you actually want the date to be a string, which brings us to issue #4:
Why are you attempting to convert the string to a date to begin with? You can not compare a date object and a string that you get from the file and ever expect them to be equal. You want to compare a string to a string. If you had some kind of validation in mind, that's fine, but use datetime.strptime and don't replace the original string; just raise an error if it doesn't convert properly.
The else clause in a for loop will execute whenever the loop terminates normally (i.e., without a break). Since you always iterate through all the lines, you will always trigger the else clause. You need to have another way to determine if you found matching items, like a boolean flag or a counter. I will show an example with a counter, since it is more general.
You never close your input file. Not a huge problem in this tiny example, but can cause major issues with bigger programs. Use a with block instead of raw open.
Your method of iterating through the file is not wrong per-se, but is inefficient. You load the entire file into memory, and then iterate over the lines. In Python, text files are already iterable over the lines, which is much more efficient since it only loads one line at a time into memory, and also doesn't make you process the file twice.
Combining all that, you can make your code look like this:
def search_projection_date():
counter = 0
with open('projections.txt','r') as projections:
date = input("Input projection date: ")
for line in projections:
projection = line.strip("\n").split("|")
if date == projection[2]:
table = [['Code:',projection[0]],
['Hall:',projection[1]],
['Date:',projection[2]],
['Start time:',projection[3]],
['End time:', projection[4]],
['Day(s):', projection[5]],
['Movie:', projection[6]],
['Price:', projection[7]]]
print(tabulate(table))
counter += 1
if not counter:
print("No projection on that date")
else:
print("Found {0} projections on {1}".format(counter, date))
I trusted your use of tabulate since I am not familiar with the module and have no intention of installing it. Keep in mind that the date verification is optional. If the user enters an invalid string, that's the end of it: you don't need to check for dates like 'aaaa' because they will just print No projection on that date. If you insist on keeping the verification, do it more like this:
from datetime import datetime
datetime.strftime(date, '%d.%m.%Y.')
That's it. It will raise a ValueError if the date does not match. You don't need to do anything with the result. If you want to change the error message, or return instead of raising an error, you can catch the exception:
try:
datetime.strftime(date, '%d.%m.%Y.')
except ValueError:
print('Bad date entered')
return
Notice that I am catching a very specific type of exception here, not using a generic except clause.
I have a directory where csv files are located. The code reads the files and creates histograms based on the data in the files.
I have made this a command prompt code where I can enter the arguments and the code will look through the csv files to see if the arguments I listed are there. I am trying to make it so that an error message comes up when I misspell a command. The following code works if the first argument is spelled correctly and the second is not, but does not display an error message if the first is misspelled and the second is correct. What's wrong?
Example: python untitled14.py "Folder" Are Perimeter DOES NOT DISPLAY ERROR MESSAGE FOR ARE
BUT python untitled14.py "Folder" Perimeter Are DOES DISPLAY ERROR FOR ARE
for x in arguments:
found_match = False
for column in df:
os.chdir(directory)
if x.endswith(column):
found_match = True
#histogram code
continue
else:
pass
if found_match==False:
print files+" " + x + " does not exist"
You have unnecessary things (and some other questionable things) in your loop logic. For example, the three lines continue; else: pass do literal nothing.
The best thing to do would be to refactor your code to call a function that would return True if all the arguments validated. You didn't provide enough code for that, so I would clean the whole thing up with:
for x in arguments:
for column in df:
os.chdir(directory)
if x.endswith(column):
#histogram code
break
else:
print "{0} {1} does not exist".format(files,x)
break #or not, depending on what you want to do
This takes advantage of the somewhat rarely-used for/else to do something if the for loop did not break - which, in your case, is an error.
If you want to really make this re-usable, you should raise an Exception instead of just printing on an error.