python 按最大长度限制截取字符串
题目说明
Complete the function ‘consistentLineLength’ taking two parameters, a filename, and a maximum length (i.e., a strictly positive integer number). The function opens the file, reads every line, and returns a list of strings where every string represents a line that is filled as much as possible without exceeding the given maximum length.
翻译:补全函数 consistentLength
,这个函数有两个参数,一个是文件名,一个是最大长度。(例如:一个严格正整数)。这个函数打开指定的文件,读取文件里的每一行并返回一个list(list的每一个元素是一个字符串类型),这里,每一个字符串是一行,这个字符串要尽可能的长但不能超过给定的最大长度。
示例
consider a file containing the following lines from ‘Alice’s Adventures in Wonderland’.
The corresponding output for length = 50 would be:
思路
观察一下,首先处理后的结果是不能以空格结尾的,但可以以标点符号或者一个完整的单词结尾。
首先是读取文本:
def consistentLineLength(filename, length):
fileHandle=open(filename)
theStr=""
for line in fileHandle.readlines():
theStr+=line
theStr存储了所有字符串,但我们还要把换行符 n
替换成空格。然后通过以空格为切割标志就能切割出所有的单词:
theStr=theStr.replace("n"," ")
strList=theStr.split(" ")
if len(strList[-1])==0:
strList.pop(-1)
接下来就是问题的关键了, resultList
是最后的结果变量。除此之外,还有一个字符串变量 tempStr
,他每一次就加一个空格和一个单词,如果超过了最大长度就重新变为空字符串变量。
tempStr=""
resultList=[]
i=0
while i<len(strList):
if tempStr=="":
if len(tempStr+strList[i])<=length:
tempStr+=strList[i]
i+=1
if i==len(strList): # 如果当前已经到了最后一个元素,那就直接添加
resultList.append(tempStr)
else:
if len(tempStr+" "+strList[i])<=length: # 如果tempStr不是空,那加入下一个单词之前先加一个空格
tempStr+=" "
tempStr+=strList[i]
i+=1
else:
resultList.append(tempStr)
tempStr=""
return resultList
完整代码:
def consistentLineLength(filename, length):
fileHandle=open(filename)
theStr=""
for line in fileHandle.readlines():
theStr+=line
theStr=theStr.replace("n"," ")
strList=theStr.split(" ")
if len(strList[-1])==0:
strList.pop(-1)
tempStr=""
resultList=[]
i=0
while i<len(strList):
if tempStr=="":
if len(tempStr+strList[i])<=length:
tempStr+=strList[i]
i+=1
if i==len(strList): # 如果当前已经到了最后一个元素,那就直接添加
resultList.append(tempStr)
else:
if len(tempStr+" "+strList[i])<=length: # 如果tempStr不是空,那加入下一个单词之前先加一个空格
tempStr+=" "
tempStr+=strList[i]
i+=1
else:
resultList.append(tempStr)
tempStr=""
return resultList
有算法online judge需求的童靴可以私信联系我。