[Tutor] how to unique the string

lina lina.lastname at gmail.com
Sun Oct 23 14:01:59 CEST 2011


On Sun, Oct 23, 2011 at 6:06 PM, Peter Otten <__peter__ at web.de> wrote:
> lina wrote:
>
>>>> tobetranslatedparts=line.strip().split()
>
> strip() is superfluous here, split() will take care of the stripping:
>
>>>> " alpha \tbeta\n".split()
> ['alpha', 'beta']
>
>>>> for residue in results:
>>>>     if residue not in unique:
>>>>         unique[residue]=1
>>>>     else:
>>>>         unique[residue]+=1
>
> There is a dedicated class to help you with that, collections.Counter:
>
>>>> from collections import Counter
>>>> results = ["alpha", "beta", "gamma", "alpha"]
>>>> unique = Counter(results)
>>>> unique
> Counter({'alpha': 2, 'beta': 1, 'gamma': 1})
>
> Counter is a subclass of dict, so the stuff you are doing with `unique`
> elswhere should continue to work.
>
>> This part I just wish the output in file like:
>>
>> {'26SER': 2, '16LYS': 1, '83ILE': 2, '70LYS': 6}
>>
>> as
>>
>> 26SER 2
>> 16LYS 1
>> 83ILE 2
>> 70LYS 6
>
> You can redirect the output of print() to a file using the `file` keyword
> argument:
>
>>>> unique = {'26SER': 2, '16LYS': 1, '83ILE': 2, '70LYS': 6}
>>>> with open("tmp.txt", "w") as f:
> ...     for k, v in unique.items():
> ...             print(k, v, file=f)

I tested it in idle3, it has no problem achieving this.

But I am getting confused later:

def translate_process(dictionary,tobetranslatedfile):
    results=[]
    unique={}
    for line in open(tobetranslatedfile,"r"):
        tobetranslatedparts=line.strip().split()
        results.append(dictionary[tobetranslatedparts[2]])
        unique=Counter(results)
        with open(base+OUTPUTFILEEXT,"w") as f:
            for residue, numbers in unique.items():
                print(residue,numbers,file=f)

it still the same in the OUTPUTFILE as before,

 $ more atom-pair_6.txt
{'26SER': 2, '16LYS': 1, '83ILE': 2, '70LYS': 6, '55HIS': 5}

Thanks,

> ...
>>>>
> $ cat tmp.txt
> 26SER 2
> 83ILE 2
> 70LYS 6
> 16LYS 1
> $
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


More information about the Tutor mailing list