so I have some code such as:
print(csv[0])
Genes = csv[0]
OutPut.write(Genes)
OutPut.write(',')
OutPut.write(csv[1])
OutPut.write(',')
try:
OutPut.write(csv[2])
except IndexError:
print("No Lethality")
OutPut.write('\n')
Basically csv has 3 objects and they should print out as this:
atp,10101010,lethal
But for some reason, if csv[0] so the first value, begining with an 'l' it is printed as:
l
sfsf,1010101010,Lethal
I have tried using a for loop etc but I always get the same issue and all the other lines which start without an 'l' work perfectly.
Thanks
It's not clear from your description why you are seeing multiple lines, here's alternative logic that may help you diagnose the problem.
Try:
OutPut.write(','.join(csv))
OutPut.write('\n' if len(csv) == 3 else "No Lethality\n")
Or:
from __future__ import print_function
print(','.join(csv), file=Output)
Related
I need this program to create a sheet as a list of strings of ' ' chars and distribute text strings (from a list) into it. I have already coded return statements in python 3 but this one keeps giving
return(riplns)
^
SyntaxError: invalid syntax
It's the return(riplns) on line 39. I want the function to create a number of random numbers (randint) inside a range built around another randint, coming from the function ripimg() that calls this one.
I see clearly where the program declares the list I want this return() to give me. I know its type. I see where I feed variables (of the int type) to it, through .append(). I know from internet research that SyntaxErrors on python's return() functions usually come from mistype but it doesn't seem the case.
#loads the asciified image ("/home/userX/Documents/Programmazione/Python projects/imgascii/myascify/ascimg4")
#creates a sheet "foglio1", same number of lines as the asciified image, and distributes text on it on a randomised line
#create the sheet foglio1
def create():
ref = open("/home/userX/Documents/Programmazione/Python projects/imgascii/myascify/ascimg4")
charcount = ""
field = []
for line in ref:
for c in line:
if c != '\n':
charcount += ' '
if c == '\n':
charcount += '*' #<--- YOU GONNA NEED TO MAKE THIS A SPACE IN A FOLLOWING FUNCTION IN THE WRITER.PY PROGRAM
for i in range(50):#<------- VALUE ADJUSTMENT FROM WRITER.PY GOES HERE(default : 50):
charcount += ' '
charcount += '\n'
break
for line in ref:
field.append(charcount)
return(field)
#turn text in a list of lines and trasforms the lines in a list of strings
def poemln():
txt = open("/home/gcg/Documents/Programmazione/Python projects/imgascii/writer/poem")
arrays = []
for line in txt:
arrays.append(line)
txt.close()
return(arrays)
#rander is to be called in ripimg()
def rander(rando, fldepth):
riplns = []
for i in range(fldepth):
riplns.append(randint((rando)-1,(rando)+1)
return(riplns) #<---- THIS RETURN GIVES SyntaxError upon execution
#opens a rip on the side of the image.
def ripimg():
upmost = randint(160, 168)
positions = []
fldepth = 52 #<-----value is manually input as in DISTRIB function.
positions = rander(upmost,fldepth)
return(positions)
I omitted the rest of the program, I believe these functions are enough to get the idea, please tell me if I need to add more.
You have incomplete set of previous line's parenthesis .
In this line:-
riplns.append(randint((rando)-1,(rando)+1)
You have to add one more brace at the end. This was causing error because python was reading things continuously and thought return statement to be a part of previous uncompleted line.
I am trying to read from a file and return solutions based on the problem that the user inputs. I have saved the text file in the same location, that is not an issue. At the moment, the program just crashes when I run it and type a problem eg "screen".
Code
file = open("solutions.txt", 'r')
advice = []
read = file.readlines()
file.close()
print (read)
for i in file:
indword = i.strip()
advice.append (indword)
lst = ("screen","unresponsive","frozen","audio")
favcol = input("What is your problem? ")
probs = []
for col in lst:
if col in lst:
probs.append(col)
for line in probs:
for solution in advice:
if line in solution:
print(solution)
The text file called "solutions.txt" holds the following info:
screen: Take the phone to a repair shop where they can replace the damaged screen.
unresponsive: Try to restart the phone by holding the power button for at least 4 seconds.
frozen: Try to restart the phone by holding the power button for at least 4 seconds.
audio: If the audio or sound doesnt work, go to the nearest repair shop to fix it.
Your question reminds me a lot of my learning, so I will try give an answer to expand on your learning with lots of print statements to consider how it works carefully. It's not the most efficient or stable approach but hopefully of some use to you to move forwards.
print "LOADING RAW DATA"
solution_dictionary = {}
with open('solutions.txt', 'r') as infile:
for line in infile:
dict_key, solution = line.split(':')
print "Dictionary 'key' is: ", dict_key
print "Corresponding solution is: ", solution
solution_dictionary[dict_key] = solution.strip('\n')
print '\n'
print 'Final dictionary is:', '\n'
print solution_dictionary
print '\n'
print 'FINISHED LOADING RAW DATA'
solved = False
while not solved: # Will keep looping as long as solved == False
issue = raw_input('What is your problem? ')
solution = solution_dictionary.get(issue)
""" If we can find the 'issue' in the dictionary then 'solution' will have
some kind of value (considered 'True'), otherwise 'None' is returned which
is considered 'False'."""
if solution:
print solution
solved = True
else:
print ("Sorry, no answer found. Valid issues are 'frozen', "
"'screen' 'audio' or 'unresponsive'")
want_to_exit = raw_input('Want to exit? Y or N? ')
if want_to_exit == 'Y':
solved = True
else:
pass
Other points:
- don't use 'file' as a variable name anywhere. It's a python built-in and can cause some weird behaviour that you'll struggle to debug https://docs.python.org/2/library/functions.html
- If you get an error, don't say "crashes", you should provide some form of traceback e.g.:
a = "hello" + 2
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-1-6f5e94f8cf44> in <module>()
----> 1 a = "hello" + 2
TypeError: cannot concatenate 'str' and 'int' objects
your question title will get you down-votes unless you are specific about the problem. "help me do something" is unlikely to get a positive response because the error is ambiguous, there's no sign of Googling the errors (and why the results didn't work) and it's unlikely to be of any help to anyone else in the future.
Best of luck :)
When I change the line "for i in file:" to "for i in read:" everything works well.
To output only the line starting with "screen" just forget the probs variable and change the last for statement to
for line in advice:
if line.startswith( favcol ) :
print line
break
For the startswith() function refer to https://docs.python.org/2/library/stdtypes.html#str.startswith
And: the advices of roganjosh are helpfull. Particularly the one "please don't use python keywords (e.g. file) as variable names". I spent hours of debugging with some bugs like "file = ..." or "dict = ...".
#!/ usr/bin/python3
import sys
def main():
for line in sys.stdin:
line = line.split()
x = -1
for word in line:
if word[-1]==word[0] or word[x-1]==word[1]:
print(word)
main()
It also prints dots at the end of the sentences, why?
And words like 'cat' and 'moon' should also be out of the question. But it also prints these words.
Can someone point me in the right direction please?
I think your problem is because the second and second last characters of 'cat' are the same.
def main():
for line in sys.stdin:
line = line.split()
x = -1
for word in line:
if (word[-1]==word[0] and len(word)<=2) or (word[x-1]==word[1] and len(word)<=4):
print(word)
or something like that, depending on your preference.
This should get rid of that pesky cat, although moon stays.
It will also include words that use upper and lower case characters, so sadly not only will moon print but also Moon, MOon, mooN and moOn.
Edit: Forgot to test for one character words (a, I etc)
import sys
def main():
for line in sys.stdin:
line = line.split()
for word in line:
uword = word.lower()
if len(uword) > 1:
if uword[0:1]==uword[-1] or (uword[1:2]==uword[-2] and len(uword) > 3):
print(word)
main()
I got it guys, understood the question wrong. This prints the right words, that I got beforehand. That cleared things up for me. This is the right code but it still gives "sys.excepthook is missing". I run this code with another code that gives a space an newline. So every space between words becomes a newline:
cat cdb.sentences| python3 newline.py| python3 word.py |head -n 5
import sys
def main():
for line in sys.stdin:
line = line.split()
for word in line:
letterword = lw = word.lower()
if len(lw) > 1:
if lw[0:1]==lw[-1] and (lw[1:2]==lw[-2]):
print(word)
main()
import sys
def main():
for line in sys.stdin:
line = line.rstrip()
text = ""
for word in line:
if word in ' ':
text=text + '\n'
else:
text=text + word
print(text)
main()
It should give the 5 first words that have the same first, last letter, -2 and 1 letters. With an white line between each one of them. First i want to solve that hook.
Thx
You are not helping yourself by answering your own question with what is essentially a completely different question in an answer.
You should have closed your original off by accepting one of the answers, if one of them helped, which it looked like they did and then asked a new question.
However, the answer to your 2nd question/answer can be found here:
http://python.developermemo.com/7757_12807216/ and it is a brilliant answer
Synopsis:
The reason this is happening is that you're piping a nonzero amount of output from your Python script to something which never reads from standard input. You can get the same result by piping to any command which doesn't read standard input, such as
python testscript.py | cd .
Or for a simpler example, consider a script printer.py containing nothing more than
print 'abcde'
Then
python printer.py | python printer.py
will produce the same error.
The following however will trap the sys.excepthook error:
import sys
import logging
def log_uncaught_exceptions(exception_type, exception, tb):
logging.critical(''.join(traceback.format_tb(tb)))
logging.critical('{0}: {1}'.format(exception_type, exception))
sys.excepthook = log_uncaught_exceptions
print "abcdfe"
def digits_plus(test):
test=0
while (test<=3):
print str(test)+"+",
test = test+1
return()
digits_plus(3)
The output is:
0+ 1+ 2+ 3+
However i would like to get: 0+1+2+3+
Another method to do that would be to create a list of the numbers and then join them.
mylist = []
for num in range (1, 4):
mylist.append(str(num))
we get the list [1, 2, 3]
print '+'.join(mylist) + '+'
If you're stuck using Python 2.7, start your module with
from __future__ import print_function
Then instead of
print str(test)+"+",
use
print(str(test)+"+", end='')
You'll probably want to add a print() at the end (out of the loop!-) to get a new-line after you're done printing the rest.
You could also use the sys.stdout object to write output (to stdout) that you have more fine control over. This should let you output exactly and only the characters you tell it to (whereas print will do some automatic line endings and casting for you)
#!/usr/bin/env python
import sys
test = '0'
sys.stdout.write(str(test)+"+")
# Or my preferred string formatting method:
# (The '%s' implies a cast to string)
sys.stdout.write("%s+" % test)
# You probably don't need to explicitly do this,
# If you get unexpected (missing) output, you can
# explicitly send the output like
sys.stdout.flush()
I have recently been learning some Python and how to apply it to my work. I have written a couple of scripts successfully, but I am having an issue I just cannot figure out.
I am opening a file with ~4000 lines, two tab separated columns per line. When reading the input file, I get an index error saying that the list index is out of range. However, while I get the error every time, it doesn't happen on the same line every time (as in, it will throw the error on different lines everytime!). So, for some reason, it works generally but then (seemingly) randomly fails.
As I literally only started learning Python last week, I am stumped. I have looked around for the same problem, but not found anything similar. Furthermore I don't know if this is a problem that is language specific or IPython specific. Any help would be greatly appreciated!
input = open("count.txt", "r")
changelist = []
listtosort = []
second = str()
output = open("output.txt", "w")
for each in input:
splits = each.split("\t")
changelist = list(splits[0])
second = int(splits[1])
print second
if changelist[7] == ";":
changelist.insert(6, "000")
va = "".join(changelist)
var = va + ("\t") + str(second)
listtosort.append(var)
output.write(var)
elif changelist[8] == ";":
changelist.insert(6, "00")
va = "".join(changelist)
var = va + ("\t") + str(second)
listtosort.append(var)
output.write(var)
elif changelist[9] == ";":
changelist.insert(6, "0")
va = "".join(changelist)
var = va + ("\t") + str(second)
listtosort.append(var)
output.write(var)
else:
#output.write(str("".join(changelist)))
va = "".join(changelist)
var = va + ("\t") + str(second)
listtosort.append(var)
output.write(var)
output.close()
The error
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
/home/a/Desktop/sharedfolder/ipytest/individ.ins.count.test/<ipython-input-87-32f9b0a1951b> in <module>()
57 splits = each.split("\t")
58 changelist = list(splits[0])
---> 59 second = int(splits[1])
60
61 print second
IndexError: list index out of range
Input:
ID=cds0;Name=NP_414542.1;Parent=gene0;Dbxref=ASAP:ABE-0000006,UniProtKB%2FSwiss-Prot:P0AD86,Genbank:NP_414542.1,EcoGene:EG11277,GeneID:944742;gbkey=CDS;product=thr 12
ID=cds1000;Name=NP_415538.1;Parent=gene1035;Dbxref=ASAP:ABE-0003451,UniProtKB%2FSwiss-Prot:P31545,Genbank:NP_415538.1,EcoGene:EG11735,GeneID:946500;gbkey=CDS;product=deferrrochelatase%2C 50
ID=cds1001;Name=NP_415539.1;Parent=gene1036;Note=PhoB-dependent%2C 36
Desired output:
ID=cds0000;Name=NP_414542.1;Parent=gene0;Dbxref=ASAP:ABE-0000006,UniProtKB%2FSwiss-Prot:P0AD86,Genbank:NP_414542.1,EcoGene:EG11277,GeneID:944742;gbkey=CDS;product=thr 12
ID=cds1000;Name=NP_415538.1;Parent=gene1035;Dbxref=ASAP:ABE-0003451,UniProtKB%2FSwiss-Prot:P31545,Genbank:NP_415538.1,EcoGene:EG11735,GeneID:946500;gbkey=CDS;product=deferrrochelatase%2C 50
ID=cds1001;Name=NP_415539.1;Parent=gene1036;Note=PhoB-dependent%2C 36
The reason you're getting the IndexError is that your input-file is apparently not entirely tab delimited. That's why there is nothing at splits[1] when you attempt to access it.
Your code could use some refactoring. First of all you're repeating yourself with the if-checks, it's unnecessary. This just pads the cds0 to 7 characters which is probably not what you want. I threw the following together to demonstrate how you could refactor your code to be a little more pythonic and dry. I can't guarantee it'll work with your dataset, but I'm hoping it might help you understand how to do things differently.
to_sort = []
# We can open two files using the with statement. This will also handle
# closing the files for us, when we exit the block.
with open("count.txt", "r") as inp, open("output.txt", "w") as out:
for each in inp:
# Split at ';'... So you won't have to worry about whether or not
# the file is tab delimited
changed = each.split(";")
# Get the value you want. This is called unpacking.
# The value before '=' will always be 'ID', so we don't really care about it.
# _ is generally used as a variable name when the value is discarded.
_, value = changed[0].split("=")
# 0-pad the desired value to 7 characters. Python string formatting
# makes this very easy. This will replace the current value in the list.
changed[0] = "ID={:0<7}".format(value)
# Join the changed-list with the original separator and
# and append it to the sort list.
to_sort.append(";".join(changed))
# Write the results to the file all at once. Your test data already
# provided the newlines, you can just write it out as it is.
output.writelines(to_sort)
# Do what else you need to do. Maybe to_list.sort()?
You'll notice that this code is reduces your code down to 8 lines but achieves the exact same thing, does not repeat itself and is pretty easy to understand.
Please read the PEP8, the Zen of python, and go through the official tutorial.
This happens when there is a line in count.txt which doesn't contain the tab character. So when you split by tab character there will not be any splits[1]. Hence the error "Index out of range".
To know which line is causing the error, just add a print(each) after splits in line 57. The line printed before the error message is your culprit. If your input file keeps changing, then you will get different locations. Change your script to handle such malformed lines.