【发布时间】: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