【发布时间】:2018-09-09 04:48:05
【问题描述】:
编写一个函数 file_in_english(filename, character_limit),它接受一个文件名(作为 str)和一个 character_limit(作为 int)。文件名是要从 Cat Latin 转换为英语的文件的名称,字符限制是可以转换的最大字符数。限制是输出中的字符总数(包括换行符)。
该函数应该返回一个字符串,其中包含所有转换后的行,其顺序与文件相同 - 记住每行末尾的换行符(即确保在每个转换行的末尾包含一个换行符以便它包含在行的长度中)。
如果超出限制(即转换后的句子会使输出超过限制),则不应将字符数超过限制的句子添加到输出中。应该在输出的末尾添加一个带有“”的行。然后应该停止对行的处理。
文件中的每一行都是一个奇怪的拉丁语句子,你的程序应该打印出每个句子的英文版本
函数应该不断添加句子,直到文件输入用完或打印的字符总数(包括空格)超过限制。
答案必须包括您对english_sentence 及其辅助函数的定义——我应该称之为english_word 或类似函数。
您必须在 file_in_english 函数中使用 while。
每个函数只能使用一个返回语句。
示例中使用的测试文件(test1.txt)有以下数据:
impleseeoow estteeoow aseceeoow
impleseeoow estteeoow aseceeoow ineleeoow 2meeoow
impleseeoow estteeoow aseceeoow ineleeoow 3meeoow
impleseeoow estteeoow aseceeoow ineleeoow 4meeoow
我的程序工作正常,只是有时它返回 None。
def english_sentence(sentence):
"""Reverse Translation"""
consonants = 'bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ'
eng_sentence = []
for coded_word in sentence.split():
if coded_word.endswith("eeoow") and (coded_word[-6] in consonants):
english_word = coded_word[-6] + coded_word[:-6]
if (coded_word[-6] == 'm') and (coded_word[0] not in consonants):
english_word = '(' + english_word + ' or ' + coded_word[:-6] + ')'
eng_sentence.append(english_word)
return " ".join(eng_sentence)
def file_in_english(filename, character_limit):
"""English File"""
newone = open(filename)
nowline = newone.readline()
characters = 0
while characters < character_limit and nowline != "":
process = nowline[0:-1]
print(english_sentence(process))
characters += len(nowline)
nowline = newone.readline()
if characters > character_limit:
return("<<Output limit exceeded>>")
ans = file_in_english('test1.txt', 20)
print(ans)
输出是:
simple test case
simple test case line (m2 or 2)
simple test case line (m3 or 3)
simple test case line (m4 or 4)
None
但我必须在每个函数中只使用一个 return 语句。我怎样才能为第二个功能做到这一点并避免输出中的“无”?
【问题讨论】:
-
您必须确保,任何应该返回某些内容的函数都适用于所有情况。您的函数
file_in_english仅针对if characters > character_limit:的情况返回一些内容 - 如果不是不是 的情况,则该函数不返回任何内容。 任何函数如果最终不从它返回任何东西,当它返回给它的调用者时会隐式返回None。
标签: python python-3.x