concatenation of string & integer NAMES within functions (python3)

This is the first posting I've done to this forum.

I have these strings, integers, and filenames declared early on...

linefeed='\n'

consonantFileHeader='Consonants found in the infile:'
vowelFileHeader='Vowels found in the infile:'

qConsonant=0
qVowel=0
ConsonantFile=open(path/tothe/file/chapters/Consonants.txt,'w+')
VowelFile=open(path/tothe/file/chapters/Vowels.txt,'w+')

the program reads in unicode glyphs one by one, and assigns each a 'type'.

if glyph='A': 
   type='VOWEL'
elif glyph='B':
   type='CONSONANT'
    ... etc...

later on, we want to add to a running count of each 'type' and write a record to a file that shows all the occurrences of each 'type'. It's routine code, that we don't want cluttering up our main function, so we call another function to do it....

if  type == 'CONSONANT':
    tabulateCONSONANT(glyph)
elif type == 'VOWEL':
    tabulateVOWEL(glyph)

at this point, two different types - two different functions. here they are...

## ------------------------------------------------------------
def tabulateCONSONANT(glyph):
    qConsonant=qConsonant+1   # bump up a counter
    if  qConsonant = 1        # on 1 write header to output
        ConsonantFile.write(consonantFileHeader)  
    ConsonantFile.write(glyph+linefeed) # write data after    
    return ;
## ------------------------------------------------------------
def tabulateVOWEL(glyph):
    qVowel=qVowel+1  # bump up counter
   if  qVowel = 1
        VowelFile.write(vowelFileHeader) # on 1, write header 
    VowelFile.write(glyph+linefeed)      # write data after
    return ;

fine and dandy, but this seems really redundant to me. even though only the actual NAMES of the values change, I have to call a different function for each type!

Is there any way write a single function that wherein we can concatenate the actual ITEM NAMES to do something like the following...?

if  type == 'CONSONANT':
    tabulateANYTHING(glyph,'Consonant')
elif type == 'VOWEL': 
    tabulateANYTHING(glyph,'Vowel')

## ------------------------------------------------------------
def tabulateANYTHING(glyph,TYPE):
# concatenate 'q'with 'TYPE' to reference 'qVowel'
    qTYPE=qTYPE+1  
    if  qTYPE = 1
# concatenate 'TYPE' with part of the filename > 'VowelFile'
    TYPEFile.write(TYPEFileHeader)  
    TYPEFile.write(glyph+linefeed)  # again,concatenation...
    return ;

if you don't know what the heck I'm trying to do here, let me know and I'll try to make it clearer...

1 answer

  • answered 2018-11-07 22:48 SuperStormer

    Create a dict or a collections.Counter and then inside tabulateANYTHING increment the value that has the key that matches TYPE

    For example, if your dict is named quantities: quantities[TYPE]+=1

    For the files, create a dict of files and write to the one that has the key that matches TYPE. Same thing for the file headers.