[Tutor] a quick Q: how to use for loop to read a series of files with .doc end

Dave Angel d at davea.name
Tue Oct 4 20:43:39 CEST 2011


On 10/04/2011 01:09 PM, lina wrote:
> But I still don't know how to get the
> statistic result of each column,
>
> Thanks for further suggestions,
>
> Best regards,
>
> lina
>
As I said before, your current code counts across a line at a time, 
while you need to count vertically.  That could be done by transposing 
the list of strings, but it's probably easier to just count them 
yourself.  So set up a list of counters, all zero, and every time you 
see a desired character, increment the corresponding counter.

Here's the existing code:

#!/bin/python

import os.path

tokens=['B','E']

for fileName in os.listdir("."):
     result=[]
     if os.path.isfile(fileName) and os.path.splitext(fileName)[1]==".xpm":
         filedata = open(fileName)
         text=filedata.readlines()
         for line in text[0:]:
             result.append({t:line.strip().count(t) for t in tokens})
         for index,r in enumerate(result):
            outfiledata=open("fileName.txt","w")


Decide first on a reasonable data arrangement for the results.   I'd suggest having a map of lists, rather than the other way around.

So initialize it to having zeroes in all the right places.

results = {}
numcolumns = len(text[23].strip())
for ch in tokens:
     results[ch] = [0] * numcolumns


and

for line in  text[23:]:
     for col, ch in enumerate(line):
         if ch in tokens:
                results[ch][col] += 1


(Untested)


-- 

DaveA



More information about the Tutor mailing list