根据长度连接unicode字符串

Concatenating unicode strings based on length

我有一个 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 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 . . . 

目的是连接小于平均长度的段。如果任何段小于平均长度,比较 previousLengthnextLength,并将 segment i 连接到更小的那个。 (第一段可能小于或大于平均值)。但是,如果任何段的长度超过平均长度,则只需附加该段即可。 newtext 应类似于 text 但应包含大于或等于平均段长度的段。 谢谢

根据我对你问题的理解,我写了下面的代码。

如果不是您想要的,能否请您说明您的要求,我可以适当地编辑代码。 - 也许尝试用伪代码编写它?

代码:

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 = ''