【问题标题】:concatenation of string & integer NAMES within functions (python3)函数内字符串和整数名称的连接(python)
【发布时间】:2018-11-07 22:23:20
【问题描述】:

这是我第一次在这个论坛发帖。

我在早期就声明了这些字符串、整数和文件名...

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+')

程序一个一个地读取 unicode 字形,并为每个字形分配一个“类型”。

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

稍后,我们想要添加每个“类型”的运行计数,并将记录写入显示每个“类型”的所有出现的文件。这是例行代码,我们不想弄乱我们的 main 函数,所以我们调用另一个函数来完成它....

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

此时,两个不同的types - 两个不同的功能。他们来了……

## ------------------------------------------------------------
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 ;

很好,花花公子,但这对我来说似乎是多余的。即使只有值的实际名称发生变化,我也必须为每种类型调用不同的函数!

有没有办法编写一个函数,我们可以在其中连接实际的 ITEM NAMES 来执行以下操作...?

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 ;

如果你不知道我到底想在这里做什么,请告诉我,我会尽量让它更清楚......

【问题讨论】:

  • 建议:以后可以考虑遵循Python风格指南PEP8

标签: python python-3.x function concatenation


【解决方案1】:

创建一个dict 或一个collections.Counter,然后在tabulateANYTHING 内增加与TYPE 匹配的键的值

例如,如果您的 dict 名为 quantitiesquantities[TYPE]+=1

对于文件,创建一个dict 文件并写入具有与TYPE 匹配的键的文件。 文件头也一样。

【讨论】:

    猜你喜欢
    • 2013-04-11
    • 2012-07-18
    • 2011-02-20
    • 1970-01-01
    • 1970-01-01
    • 2018-11-18
    • 1970-01-01
    • 2019-11-23
    相关资源
    最近更新 更多