Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.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 textwrap和忽略字符串的部分_Python_String_Word Wrap - Fatal编程技术网

Python textwrap和忽略字符串的部分

Python textwrap和忽略字符串的部分,python,string,word-wrap,Python,String,Word Wrap,这里完全是初学者,第一次在这个好地方发布。使用Python 3.2.3 快速描述 我想换行和字符填充字符串,但是字符串的某些部分应该被忽略 背景 我正在使用一个从.txt文件输出文本的程序,但没有换行符或换行符。因为我现在不能编辑程序的功能,所以我唯一的选择就是编辑文本文件 该程序使用固定大小的单空格字体,因此我知道每个文件和行的具体字符数。我使用程序的硬空间命令\ \ uu作为每个包装行(最后一行除外)的填充字符。硬空间命令临时转换为#,以在脚本中保持正确的字符计数 下面是我的文本编辑脚本的一

这里完全是初学者,第一次在这个好地方发布。使用Python 3.2.3

快速描述

我想换行和字符填充字符串,但是字符串的某些部分应该被忽略

背景

我正在使用一个从.txt文件输出文本的程序,但没有换行符或换行符。因为我现在不能编辑程序的功能,所以我唯一的选择就是编辑文本文件

该程序使用固定大小的单空格字体,因此我知道每个文件和行的具体字符数。我使用程序的硬空间命令\ \ uu作为每个包装行(最后一行除外)的填充字符。硬空间命令临时转换为#,以在脚本中保持正确的字符计数

下面是我的文本编辑脚本的一个经过修改和简化的版本:

from textwrap import TextWrapper

linelist = ['"I thought that...\p glob was a weird\_name for a module."',
"Nobody can tell a secret from the \p\shake{1}sky unless they borrow wings \
from their neighbors. It's a pity, really. Life on the ground can be a bore.",
'\shake{6} The ground was trembling. What\wait{150} \pcould\wait{1300} the \
townfolk do? Even the pizzeria was closed.']

ww = TextWrapper(break_on_hyphens="False", width=30)

def space_wordwrap(wwl):
    out = []
    for ln in ww.wrap(wwl):
        out.append("{0:#<{1:d}}".format(ln, ww.width))
        #just a quick workaround for simpler print output for SO question
        if not ln in ww.wrap(wwl)[-1]:
            out[-1] += "\n"
    return ''.join(out).rstrip('#')

for line in linelist:
    #line = line.replace('\\_', '#')
    if len(line) > ww.width:
        line = space_wordwrap(line)
    #line = line.replace('#', '\\_')
    print(line + "\n")
我想我必须从行中删除程序命令,然后在换行后将它们插入各自的位置,但我不确定最干净的方法是什么

我最初的想法是找到前面的单词(如果有的话)并将其用作参考。我会检查是否有一个\被使用,在它前面找一个空格,后面没有\,将前面的单词存储在一个列表中,然后在单词上插入一个顺序号,以防行中有许多类似的单词

唷!这是一个相当冗长的描述。关于如何做有什么建议吗?此外,如果我的任何编码实践看起来很愚蠢,我很乐意知道。毕竟还是刚刚开始。:-]


提前谢谢

有很多方法可以做到这一点,但是

预处理文本,删除命令并记住它们所在的位置,作为文本开头的字符偏移量

然后把你的话包装起来

最后,重新插入命令。您可能需要逐个字符逐步查看最终文本,以便在计算命令字符位置时可以忽略#字符和/n和/r


一个可能足够好的近似解决方案是,将命令替换为您知道在重新格式化时不会出现在源文本中的占位符字符,例如@、~、&,等等,然后将命令放回原处。输出将不会被完美地包装,因为某些行的结尾可能比需要的空间更多。

预处理并重新插入它。想得同样多,只是用了一种更笨拙的方法。谢谢你!
"I thought that...\p glob was#
a weird\_name for a module."

Nobody can tell a secret from#
the \p\shake{1}sky unless they
borrow wings from their#######
neighbors. It's a pity,#######
really. Life on the ground can
be a bore.

\shake{6} The ground was######
trembling. What\wait{150}#####
\pcould\wait{1300} the########
townfolk do? Even the pizzeria
was closed.