【问题标题】:Concatenating unicode strings based on length根据长度连接 unicode 字符串
【发布时间】:2018-03-30 11:16:37
【问题描述】:

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

【问题讨论】:

    标签: python unicode concatenation string-concatenation


    【解决方案1】:

    根据我对您问题的理解,我编写了以下代码。

    如果不是您要的内容,请说明您的要求,我可以适当地编辑代码。 - 可以尝试用伪代码写吗?

    代码:

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

    【讨论】:

    • 这应该接近我想要的想法。我已经按照您的建议编辑了问题。可能有助于澄清我的预期结果。
    猜你喜欢
    • 2013-04-03
    • 1970-01-01
    • 2016-08-21
    • 2012-01-19
    • 2016-07-08
    • 2013-11-25
    • 2017-07-18
    • 1970-01-01
    相关资源
    最近更新 更多