Python 基于长度连接unicode字符串
我有一个unicode文本,它被分成不同的段。我想根据它们的长度连接它们,但要确保没有重复的段。 以下是psuedo cdoe:Python 基于长度连接unicode字符串,python,unicode,concatenation,string-concatenation,Python,Unicode,Concatenation,String Concatenation,我有一个unicode文本,它被分成不同的段。我想根据它们的长度连接它们,但要确保没有重复的段。 以下是psuedo cdoe: i=0 text = 'whole text' spaceString = ' ' avgLength = len(text)/len(total number of segments) newtext=[] previousLength = len(segments[i-1]) nextLength = len(segments[i+1]) for each seg
i=0
text = 'whole text'
spaceString = ' '
avgLength = len(text)/len(total number of segments)
newtext=[]
previousLength = len(segments[i-1])
nextLength = len(segments[i+1])
for each segment [i]:
if len(segments[i])<avgLength:
compare previousLength and nextLength and get the lower result
Concatenate segment[i] to either segment[i+1] or segment[i-1] (and attach to newtext) depending on which is lower
else if segment[i]>=avgLength:
Attach segment[i] to newtext and move to next segment
elif . . .
i=0
text='全文'
空格字符串=“”
avgLength=len(文本)/len(段总数)
newtext=[]
前一个长度=len(段[i-1])
nextLength=len(段[i+1])
对于每个段[i]:
如果len(段[i])=平均长度:
将段[i]附加到新文本并移动到下一段
埃利夫。
其目的是连接小于平均长度的线段。如果任何段小于平均长度,则比较previousLength
和nextLength
,并将段i
与较小的段连接。(第一段可能小于或大于平均值)。但是,如果任何段超过平均长度,只需附加该段即可newtext
应与text
类似,但应包含大于或等于平均段长度的段。
谢谢根据我对你问题的理解,我编写了以下代码 如果这不是你正在寻找的,请你澄清你的要求,我可以适当地编辑代码。-也许试着用psuedo代码来写 代码:
temp_字符串=“”
对于范围内的i(len(段)):
如果len(段[i])=avgLength,则将其添加到新文本并重置临时字符串
如果len(临时字符串)>=平均长度:
newtext.append(临时字符串)
临时字符串=“”
其他:
#如果len(段[i])>=平均长度:
#如果该段位于临时字符串中,请附加临时字符串并将其重置
如果临时字符串中的段[i]:
newtext.append(临时字符串)
临时字符串=“”
其他:
#如果段不在临时字符串中,请添加空格和段
temp_string+=spaceString+段[i]
#添加到新文本并重置
newtext.append(临时字符串)
临时字符串=“”
这应该接近我想要的想法。我已经按照你的建议编辑了这个问题。也许这有助于澄清我的预期结果。
temp_string = ''
for i in range(len(segments)):
if len(segments[i]) < avgLength:
#if it is in the temp string do nothing to avoid repitition
#else add to temp_string
if segments[i] in temp_string:
continue
else:
temp_string += spaceString + segments[i]
#if temp_string is not >= avgLength, add it to newtext and reset temp_string
if len(temp_string) >= avgLength:
newtext.append(temp_string)
temp_string = ''
else:
#when if len(segments[i]) >= avgLength:
#if the segment is in the temp_string, append temp_string and reset it
if segments[i] in temp_string:
newtext.append(temp_string)
temp_string = ''
else:
#if segment is not in the temp_string, add space and segment
temp_string += spaceString + segments[i]
#add to newtext and reset
newtext.append(temp_string)
temp_string = ''