On 23/10/11 09:33, lina wrote:
I have a further question:
> Welcome anyone help me transform the code to another form.
What form would you like it transformed to?
A flow chart? Another programming language? A different style of Python
(Functional programming or OOP maybe?)
I'm not sure what you want here?
In the meantime I'll offer some general comments:
#!/usr/bin/python3
import os.path
mapping={}
DICTIONARYFILE="dictionary.pdb"
TOBETRANSLATEDFILEEXT=".out"
OUTPUTFILEEXT=".txt"
def generate_dict(dictionarysourcefile):
for line in open(dictionarysourcefile,"r").readlines():
You don't need the readlines(). Just
use
for line in open(dictionarysourcefile,"r"):
That will work just as well.
parts=line.strip().split()
mapping[parts[2]]=parts[0]
def translate_process(dictionary,tobetranslatedfile):
results=[]
unique={}
for line in open(tobetranslatedfile,"r").readlines():
tobetranslatedparts=line.strip().split()
results.append(dictionary[tobetranslatedparts[2]])
for residue in results:
if residue not in unique:
unique[residue]=1
else:
unique[residue]+=1
You can replace the if/else with the get() metjod of a dictionary:
unique[residue] = unique.get(residue,0) + 1
get returns the current value and if the value is not there it returns
the second parameter(zero here)
for residue, numbers in unique.items():
print(residue,numbers)
with open(base+OUTPUTFILEEXT,"w") as f:
f.write(str(unique)) ########### How can I output the
results the same as the print one. Thanks.
create a string before you write it:
mystr = str(residue) + str(numbers)
is the simplest way. However you may prefer to format the string in
another way first. But thats your choice...
if __name__=="__main__":
generate_dict(DICTIONARYFILE)
for infilename in os.listdir("."):
base, ext = os.path.splitext(infilename)
if ext == TOBETRANSLATEDFILEEXT:
translate_process(mapping, infilename)
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
_______________________________________________
Tutor maillist - Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor