I just want to only print my reslut to Spss cell called "vysledek", in python script.
Ivot only two arrays, so i comper this arrays and count only in how many cases is the second one bigger than firts one, and wants to print the reslut to vysledek.
Begin program.
import spss, spssaux
spssaux.OpenDataFile('C:\Users\šoťa\Desktop\datacssd.sav')
dlist = ['PARLAMENTCSSD2010']
ilist = ['KRAJCSSD2012']
vlist = ['VYSLEDKY']
ddim = Len(dlist)
idim = Len(ilist)
For i In range(ddim):
If dlist[x] < ilist[x]:
Print ('the ilist is higher in cases: + '.')
spss.Submit(r"""
vlist[1]=vlist[1]+1
End program.
Not sure exactly how the SPSS interface works but I suspect it's not working because nearly every line in your code is invalid Python syntax. Try converting to the the following:
import spss, spssaux
spssaux.OpenDataFile('C:\Users\šoťa\Desktop\datacssd.sav')
dlist = ['PARLAMENTCSSD2010']
ilist = ['KRAJCSSD2012']
vlist = ['VYSLEDKY']
ddim = len(dlist)
idim = len(ilist)
for i in range(ddim):
if dlist[x] < ilist[x]:
print ('the ilist is higher in cases: + .')
spss.Submit("vlist[1]=vlist[1]+1")
I suspect that some capitalization-crazy tool broke the original post, but the problem remains the use of the Submit api. The argument to Submit is one or more lines of SPSS syntax, not what is shown above. If you accumulate the count within the Python code (and not in the character string vlist), you can just print it as an ordinary Python print statement.
If you want to turn this into a nice pivot table, you can use the
spss.SimplePivotTable api.
Related
I'm new to BioPython and I'm trying to import a fasta/fastq file and iterate through each sequence, while performing some operation on each sequence. I know this seems basic, but my code below for some reason is not printing correctly.
from Bio import SeqIO
newfile = open("new.txt", "w")
records = list(SeqIO.parse("rosalind_gc.txt", "fasta"))
i = 0
dna = records[i]
while i <= len(records):
print (dna.name)
i = i + 1
I'm trying to basically iterate through records and print the name, however my code ends up only printing "records[0]", where I want it to print "records[1-10]". Can someone explain why it ends up only print "records[0]"?
The reason for your problem is here:
i = 0
dna = records[i]
Your object 'dna' is fixed to the index 0 of records, i.e., records[0]. Since you are not calling it again, dna will always be fixed on that declaration. On your print statement within your while loop, use something like this:
while i <= len(records):
print (records[i].name)
i = i + 1
If you would like to have an object dna as a copy of records entries, you would need to reassign dna to every single index, making this within your while loop, like this:
while i <= len(records):
dna = records[i]
print (dna.name)
i = i + 1
However, that's not the most efficient way. Finally, for you to learn, a much nicer way than with your while loop with i = i + 1 is to use a for loop, like this:
for i in range(0,len(records)):
print (records[i].name)
For loops do the iteration automatically, one by one. range() will give a set of integers from 0 to the length of records. There are also other ways, but I'm keeping it simple.
Having a lot of problems with everything today it seems, first time asking a question and I can't even get my code on here correctly!
Essentially what I'm hoping to do, is to import data from a csv file and use it to select and display images using pygame e.g.
screen.blit(row[0],(0,0))
Where row[0] is Rat1 in the csv file, which has been defined in my code as:
Rat1 = pygame.image.load('Rat1.jpg').convert()
However this throws up "argument 1 must be pygame.Surface, not str", which is fair enough, but I'm really struggling to find a way around this and have found some rather bizarre goings on, bizarre to me at least.
I'm new to this, so the best way I can think to get around this, is to change the row[0] in the csv file to 1, and then to import that to my program and create an integer variable from it, e.g.
x = row[0]
int(x)
if x == 1:
x = Rat1
and then plug x in to pygame, e.g.
screen.blit(x,(0,0))
This works if I just have x = Rat1 as a global variable, however doing it as above doesn't change x to = 1, it stays as row[x] so it just doesn't like it.
It boils down to this happening when I tried to test it a bit...
import csv
out = open("CSVTest.csv","rb")
data = csv.reader(out)
data = [row for row in data]
out.close()
print row[0] #this causes it to print a 1, so I know
#it's working and reading as it should
x = row[0] #make a variable
int(x) #doesn't throw up an error, so I assume it
#has changed the csv string to an integer
print x #prints a 1 again
if x == 1:
print "hello?" #doesn't print, so clearly doesn't
#recognise x as an integer
if x == 49: #I'm getting desperate now, ASCII 1?!
print "hello?!" #No joy
So what on earth is it, it doesn't seem to be your standard string, as won't convert obviously in to an integer.
I've tried pygame.image.fromstring(), where the answer probably lies, but I can't get it to work.
Can anyone point out what is wrong with it all and how I can easily call data from a csv file and at least get it recognised as an integer or even better, inserted in to a bit of pygame code and displayed?
I've read things from csv files and displayed images with pygame without a hitch, but getting the two to mate seems tough, beyond me certainly.
Any help is much appreciated!
int() is the Python standard built-in function to convert a string into an integer value. You call it with a string containing a number as the argument, and it returns the number converted to an actual integer:
print int("1") + 1
The above prints 2.
If you know the structure of your list (that it simply contains lists, only one level), you could do this:
T2 = [map(int, x) for x in T1]
Or...
Try this.
x = "1"
x is a string because it has quotes around it, but it has a number in it.
x = int(x)
Since x has the number 1 in it, I can turn it in to a integer.
To see if a string is a number, you can do this.
def is_number(var):
try:
if var == int(var):
return True
except Exception:
return False
x = "1"
y = "test"
x_test = is_number(x)
print(x_test)
It should print to IDLE True because x is a number.
y_test = is_number(y)
print(y_test)
It should print to IDLE False because y in not a number.
I'm having some trouble with my code in python. I just started learning input and output in class, and how to have python read in data from text files(barely. I'm still a huge beginner). Anyways, my assignment is that I have to have my program read in data from a file and run it through my program. Problem is, I don't have a good idea on how to do that and was wondering if you guys could help me out. The text file just contains a huge life of numbers for python to use in my program. My program finds the mean, median, and standard deviation of a list of numbers that are given to it. Now, instead of user input data, my professor wants python to use data from a file that was already pre-written.
My code:
import math
def mean(values):
average = sum(values)*1.0/len(values)
return average
def deviation(values):
length = len(values)
m = mean(values)
total_sum = 0
for i in range(length):
total_sum += (values[i]-m)**2
root = total_sum*1.0/length
return math.sqrt(root)
def median(values):
if len(values)%2 != 0:
return sorted(values)[len(values)//2]
else:
midavg = (sorted(values)[len(values)//2] + sorted(values)[len(values)//2-1])//2.0
return midavg
def main():
x = [15, 17, 40, 16, 9]
print (mean(x))
print (deviation(x))
print (median(x))
main()
Now, I have to edit my code so it opens the file, takes the data, and reads the data through my equations. Only problem is, I don't have a good idea on how to do that. Could anyone please help?
I've tried basic input and output myself, but it's done no justice in helping me with the bigger picture.
def main():
total=0
input = open('Stats.txt')
for nextline in input:
mylist = nextline.split()
for n in mylist:
total+=int(n)
print(total)
You have to fill your list from the file.
Open the file and iterate over the lines. Convert the content of the line to an integer and append it to your list. If you don't cxonvert the data you'll get strings and those won't work with mathematical operations. Close your file.
Now work with your list.
filename = 'newfile.txt'
data = []
source = open(filename)
for line in source:
data.append(int(line))
source.close()
print(mean(data))
print(deviation(data))
# more stuff with data
There is a way to let Python close the file for you so you won't have to remember it.
with open(filename) as source:
for line in source:
data.append(int(line))
According to your edit this might not be what you want. If the numbers are in one line, rather than one number per line, you'll have to take a different approach (split).
I'm having some trouble here. For my CS assignment, I have to have python take data from a file on my pc and run the data through my program.
So, this code works fine on http://repl.it/languages/Python, but not in python. I'm assuming because my line of code has some Python 2.0 lines of code? I can't seem to fix it. Can you guys help? And, another small question except this one. I have to input some code in my program to take data from a file and run it through my program as I stated above. I have this.
import math
def mean(values):
average = sum(values)*1.0/len(values)
return average
def deviation(values):
length = len(values)
m = mean(values)
total_sum = 0
for i in range(length):
total_sum += (values[i]-m)**2
root = total_sum*1.0/length
return math.sqrt(root)
def median(values):
if len(values)%2 != 0:
return sorted(values)[len(values)/2]
else:
midavg = (sorted(values)[len(values)/2] + sorted(values)[len(values)/2-1])/2.0
return midavg
def main():
x = [15, 17, 40, 16, 9]
print mean(x)
print deviation(x)
print median(x)
main()
How do I specifically have the program take data from the file and run it through my program? The data is just a bunch of numbers, by the way. It's been giving me trouble for some hours now. Thanks if you can help out.
This is what I know about the opening/closing file stuff so far
f = open("filename.txt")
data = f.readlines()
f.close()
Apparently you are using python2.x:
I'm assuming because my line of code has some Python 2.0 lines of code?
So yes, you do have a problem: In python3.x, print became a function.
Thus, your prints need to be changed:
print mean(x)
print deviation(x)
print median(x)
Becomes
print(mean(x))
print(deviation(x))
print(median(x))
Also, your part about opening and closing files is unclear.
I´m experiencing problems with my code.
I can´t get it to append to the list not_found as well as it loops twice for some reason.
Can anyone point me in the right direction? The match works for my_track, but it doesn't when it doesn't match.
# coding: utf-8
#!/usr/bin/env python
import spotimeta
import sys
import time
my_tracks = raw_input("Please enter a sentence: ").title().split()
playlist = []
real_playlist = []
not_found = []
def check_track(track_name, my_track, track_href):
if track_name == my_track:
playlist.append(track_href)
return 1
# make sure the user does not input a single word as input
if (len(my_tracks) > 1):
path = my_tracks[1]
else:
sys.exit("Invalid input, please enter a sentence.")
# let's search
for my_track in my_tracks:
match = 0
print "Searching for '%s'\n" % (my_track),
data = spotimeta.search_track(my_track)
for result in data['result']:
if not match == 1:
try:
match = check_track(result["name"],my_track,result["href"])
except Exception, e:
error = "not available"
else:
if data['total_results'] > 0:
not_found.append(my_track)
You should try debugging it. One of the simplest ways of debugging is add the lines:
import pdb
pdb.set_trace()
Then when you run the script it will stop at the set_trace line in the debugger.
Check out http://docs.python.org/library/pdb.html for more information.
From my understanding you're trying to do something like:
for my_track in my_tracks:
print "Searching for '%s'\n" % (my_track),
data = spotimeta.search_track(my_track)
for result in data['result']:
if result['name'] == my_track:
playlist.append(result['href'])
elif data['total_results'] > 0:
not_found.append(my_track)
Will this more or less work for you?
Please help me to understand.
Right off the bat, I'm noticing two things.
First, you're checking data['total_results'] a bit late; if the total results value is greater than zero (wait, what?), then you want to add it to the list immediately and move on without parsing the data. I would, after the call from spotimeta.search_track(), check to see if this is the data you don't want (then subsequently add it into the list).
Second, I'm confused about the intention of your for loop. If you're going through it to only find one item, then you can use the in statement (my_track in result).