编写一个函数file_in_english(filename,character_limit),该函数采用文件名(作为str)和character_limit(作为int)。文件名是要从Code Latin转换为英语的文件的名称,字符数限制是可以转换的最大字符数(包括换行符)。
该函数应返回一个字符串,该字符串包含与文件相同的所有转换行
如果超过了限制(即,转换后的句子将使输出超过限制),那么将字符数超过限制的句子不应添加到输出中。应该在输出末尾添加带有“ <>”的行。然后应该停止行的处理。
文件中的每一行将都是拉丁语代码中的一个句子,您的程序应打印出每个句子的英文版本
您的函数应不断添加句子,直到用尽文件输入或打印的字符总数(包括空格)超过限制为止。
输入文本文件具有以下数据:
aughterleeoow anmeeoow essaymeeoow onmeeoow heteeoow eaningmeeoow ofmeeoow
heteeoow omicceeoow ybeeoow enriheeoow ergsonbeeoow embermeeoow ofmeeoow
heteeoow institutemeeoow rofessorpeeoow atmeeoow
heteeoow ollegeceeoow edeeoow rancefeeoow authorisedmeeoow ranslationteeoow
ybeeoow loudesleyceeoow reretonbeeoow .leeoow esmeeoow .leeoow (paris),meeoow
.a.meeoow (cantab)meeoow andmeeoow redfeeoow othwellreeoow .a.beeoow
(london)meeoow ranslators'teeoow refacepeeoow histeeoow ork,weeoow ybeeoow
rofessorpeeoow ergson,beeoow asheeoow eenbeeoow evisedreeoow inmeeoow
etaildeeoow ybeeoow heteeoow authormeeoow imself,heeoow andmeeoow heteeoow
resentpeeoow ranslationteeoow ismeeoow heteeoow onlymeeoow authorisedmeeoow
one.meeoow orfeeoow histeeoow
这是我的程序: (期望输出与我的输出不同)
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"""
space = ""
newone = open(filename)
nowline = newone.readline()
characters = 0
while characters < character_limit and nowline != "":
process = nowline[0:-1]
space += english_sentence(process)+'\n'
characters += len(nowline)
nowline = newone.readline()
if characters > character_limit:
space += "<<Output limit exceeded>>"
return space
Test Case:
ans = file_in_english('big_test.txt', 112)
print(ans)
> Obtained Output:
laughter
(man or an) (messay or essay) (mon or on) the (meaning or eaning) (mof or
of) the comic by henri bergson
<<Output limit exceeded>>
Exected Output:
laughter
(man or an) (messay or essay) (mon or on) the (meaning or eaning) (mof or of) the comic <<Output limit exceeded>>
Test Case 2:
ans = file_in_english('big_test.txt', 8)
print(ans)
Obtained Output:
laughter
<<Output limit exceeded>>
EXPECTED Output:
<<Output limit exceeded>>
请告知我要去哪里了。
答案 0 :(得分:0)
在将当前翻译的句子附加到输出characters
之后,您正在检查长度(存储在space
变量中)。在添加到输出之前,应检查长度是否超过限制:
def file_in_english(filename, character_limit):
space = ""
newone = open(filename)
newline = english_sentence(newone.readline()) + '\n'
while newline != '\n' and len(space) + len(newline) <= character_limit:
space += newline
newline = english_sentence(newone.readline()) + '\n'
if len(space) + len(newline) > character_limit:
space += "<<Output limit exceeded>>"
return space