基于长度连接unicode字符串

2024-04-19 23:01:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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类似,但应该包含大于或等于平均片段长度的片段。 谢谢


Tags: andtotext文本lenifunicodesegment
1条回答
网友
1楼 · 发布于 2024-04-19 23:01:36

根据我对你问题的理解,我编写了以下代码。你知道吗

如果它不是你要找的,请你澄清你的要求,我可以适当地编辑代码。-也许试着用psuedo代码写?你知道吗

代码:

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

相关问题 更多 >