Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用左右边距和固定行长写入文件的Python代码_Python_Margin_Margins_Layoutmargins - Fatal编程技术网

用左右边距和固定行长写入文件的Python代码

用左右边距和固定行长写入文件的Python代码,python,margin,margins,layoutmargins,Python,Margin,Margins,Layoutmargins,我正在编写一个Python程序,该程序读取一个文件,然后将其内容写入另一个文件,并添加边距。页边距为用户输入,行长不得超过80个字符 我编写了一个递归函数来处理这个问题。在很大程度上,它正在发挥作用。但是,任何新段落前的2行显示为右侧输入的缩进,而不是保留左侧缩进。 关于为什么会发生这种情况有什么线索吗 代码如下: left_Margin = 4 right_Margin = 5 # create variable to hold the number of characters to wit

我正在编写一个Python程序,该程序读取一个文件,然后将其内容写入另一个文件,并添加边距。页边距为用户输入,行长不得超过80个字符

我编写了一个递归函数来处理这个问题。在很大程度上,它正在发挥作用。但是,任何新段落前的2行显示为右侧输入的缩进,而不是保留左侧缩进。 关于为什么会发生这种情况有什么线索吗

代码如下:

left_Margin = 4
right_Margin = 5

# create variable to hold the number of characters to withhold from line_Size
avoid = right_Margin
num_chars = left_Margin


def insertNewlines(i, line_Size):
    string_length = len(i) + avoid + right_Margin
    if len(i) <= 80 + avoid + left_Margin:
        return i.rjust(string_length)
    else:
        i = i.rjust(len(i)+left_Margin)
        return i[:line_Size] + '\n' + ' ' * left_Margin + insertNewlines(i[line_Size:], line_Size)

with open("inputfile.txt", "r") as inputfile:
    with open("outputfile.txt", "w") as outputfile:
        for line in inputfile:
            num_chars += len(line)
            string_length = len(line) + left_Margin
            line = line.rjust(string_length)
            words = line.split()
            # check if num of characters is enough
            outputfile.write(insertNewlines(line, 80 - avoid - left_Margin))
但结果是:

     ____Poetry is a form of literature that uses aesthetic and rhythmic
     ______qualities of language—such as phonaesthetics, sound symbolism, and
     ______metre—to evoke meanings in addition to, or in place of, the prosai
          ________c ostensible meaning. 
    _____Poetry has a very long history, dating back to prehistorical ti
    _____mes with the creation of hunting poetry in Africa, and panegyric an
    _____d elegiac court poetry was developed extensively throughout the his
          _____tory of the empires of the Nile, Niger and Volta river valleys.

这并不适合Python中的递归解决方案。下面是您问题的格式化部分的命令式/迭代式解决方案(我假设您可以将其写入文件)。代码假定段落由两个连续的换行符(
'\n\n'
)表示

上面的输出是:

01234567890123456789012345678901234567890123456789012345678901234567890123456789
    Poetry is a form of literature that uses aesthetic and rhythmic
    qualities of language such as phonaesthetics, sound symbolism, and
    metre to evoke meanings in addition to, or in place of, the prosaic
    ostensible meaning.

    Poetry has a very long history, dating back to prehistorical times with
    the creation of hunting poetry in Africa, and panegyric and elegiac
    court poetry was developed extensively throughout the history of the
    empires of the Nile, Niger and Volta river valleys.

您的问题不是询问用户文件名,因此我对您的问题进行了编辑,以删除不相关的代码。你的缩进和间距到处都是,所以我也把它修好了。最后,
line
是一个很好的变量名,用于存储文件中的行,
i
非常令人惊讶(因为它主要用于在循环上下文中存储整数)。如果您也提供输入文件的文本(而不仅仅是输出的外观),那就太好了…Eva:您当前问题中的代码似乎没有产生您所说的当前结果。还不清楚代码如何以及在何处检测和处理新段落。另外,a@thebjorn已经提到,请提供原始输入文件的内容。感谢您的反馈!在我的程序中,我从文件中读取文本。既然文件不采用split(),这将如何更改变量txt?此外,我还遇到了一个编译器问题,因为它不再检测输入文件。有什么想法吗?文本处理程序的结构是:(1)读取文本,(2)处理文本,(3)编写文本。我的代码完成了(2)。您可以将文本读入
txt
变量,例如通过
txt=open('inputfile.txt')。read()
。对于第(3)部分,打印函数有一个
file=..
参数,您可以使用它。附言:我不会为你的家庭作业问题提供一个全包解决方案。如果您有特定的问题,您应该问特定的问题(即“…我遇到了编译器问题…”是您的问题,而不是我的问题。希望您理解;-)
txt = """
Poetry is a form of literature that uses aesthetic and rhythmic qualities of language—such as phonaesthetics, sound symbolism, and metre—to evoke meanings in addition to, or in place of, the prosaic ostensible meaning.

Poetry has a very long history, dating back to prehistorical times with the creation of hunting poetry in Africa, and panegyric and elegiac court poetry was developed extensively throughout the history of the empires of the Nile, Niger and Volta river valleys.
"""


def format_paragraph(paragraph, length, left, right):
    """Format paragraph ``p`` so the line length is at most ``length``
       with ``left`` as the number of characters for the left margin,
       and similiarly for ``right``.
    """
    words = paragraph.split()
    lines = []
    curline = ' ' * (left - 1)  # we add a space before the first word

    while words:
        word = words.pop(0)  # process the next word

        # +1 in the next line is for the space.
        if len(curline) + 1 + len(word) > length - right:
            # line would have been too long, start a new line
            lines.append(curline)
            curline = ' ' * (left - 1)
        curline += " " + word

    lines.append(curline)

    return '\n'.join(lines)


# we need to work on one paragraph at a time
paragraphs = txt.split('\n\n')

print('0123456789' * 8)  # print a ruler..

for paragraph in paragraphs:
    print(format_paragraph(paragraph, 80, left=4, right=5))
    print()  # next paragraph
01234567890123456789012345678901234567890123456789012345678901234567890123456789
    Poetry is a form of literature that uses aesthetic and rhythmic
    qualities of language such as phonaesthetics, sound symbolism, and
    metre to evoke meanings in addition to, or in place of, the prosaic
    ostensible meaning.

    Poetry has a very long history, dating back to prehistorical times with
    the creation of hunting poetry in Africa, and panegyric and elegiac
    court poetry was developed extensively throughout the history of the
    empires of the Nile, Niger and Volta river valleys.