我如何在python中获得文本的充分证明

时间:2018-11-24 01:25:19

标签: python-3.x

# -*- coding: utf-8 -*-
import io


def main():
    global get_user_input
    global stringInput
    global width
    stringInput = ''
    width = ''
    get_user_input = input("Please enter a string to Justify and the width to justify at using a | to separate the string and width: " )

def left_justify(stringInput, width) :
    #single line only
    return ' '.join(stringInput).ljust(width)

def justify(stringInput, width) :
    output = io.StringIO()
    justifyInput = stringInput.split(' ')
    line = []             # List of words in current line.
    col = 0               # Starting column of next word added to line.

    for word in justifyInput:
        if line and col + len(word) > width:
            if len(line) == 1:
                output.write(left_justify(line, width))
            else:
                # After n + 1 spaces are placed between each pair of words, 
                #there are spaces left over; these result in wider spaces at the left.
                n, r = divmod(width - col + 1, len(line) - 1)
                narrow = ' ' * (n + 1)
                if r == 0:
                    output.write(narrow.join(line))
                else:
                    wide = ' ' * (n + 2)
                    output.write(wide.join(line[:r] + [narrow.join(line[r:])]))
            line, col = [], 0
        line.append(word)
        col += len(word) + 1
    if line:
        output.write(left_justify(line, width))
    return output.getvalue()

def print_the_output():
    print(justify(stringInput, width))

main()

if "|" not in get_user_input :
    print("please ensure you used a | to separate the string from the jusfitication width")
elif get_user_input.find('|') != -1:    
    try:
        stringInput = get_user_input.split('|')[0].strip('|').lstrip(' ')
        val = str(stringInput)
        print("\nthe following string will be processed for justification: %s" %stringInput.strip('|'))
    except ValueError:
        print("please ensure the string to justify is text")
    try:
        width = int(get_user_input.split('|')[1].strip('|'))
        val = int(width)
        print("\nThe justification will occur at a width of: %s" %width)
    except ValueError:
        print("\nplease ensure your justification width is an integer")
    else:
        print(' ')
        print_the_output()

我有点卡在这里:

  1. 当字符串只有1行时,我不确定它是否使用指定的整个宽度。从而使字符串在整个宽度上都是合理的。
  2. 要验证是否正在发生#1,我需要找到一种方法来显示字符串中每个字符的位置,从而证明它使用了整个宽度量。 (因此,如果有10个字符,那么01234567890会计算所有内容,包括空格)
  3. 从#2开始,我想找出一种方法来记录索引为8的传入字符串字符并将其存储,并检查该字符是否与输出匹配并检查总长度与宽度匹配。

在我看来,这将是单元测试:字符是否匹配且输出长度是否匹配请求的宽度。

0 个答案:

没有答案