这里完全初学者编码器,在这个好地方首先发布。使用Python 3.2.3。Python的textwrap和忽略字符串的部分
简单描述
我想换行和字符填充字符串,但是字符串的某些部分应该被忽略。
背景
我用从.txt文件输出的文本,但没有换行或换行的程序工作。由于至少现在我无法编辑程序的功能,我唯一的选择是编辑文本文件。
该程序使用固定大小的等宽字体,所以我知道每个文件&行的具体字符数。我将程序的硬空间命令\ _用作每个包装行(除了最后一个)的填充字符。硬空间命令会暂时转换为#以在我的脚本中保留正确的字符数。
这里是我的文字编辑脚本的,而改变和简化版本:
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")
问题
在文本文件中的许多线在它们的程序的命令。这些命令不会被程序显示为文本,但它们的位置很重要......并且它们被放置在可显示文本的任何位置。这抛出了wordwrap的字符数。
有4个命令:\p \wait{100} \stop{200} \shake{1}
。例子见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.
我想我必须删除从行程序命令,然后将其插入回自动换行之后他们各自的位置,但我不知道是什么将是最干净的方式去做。
我最初的想法是找到前面的单词(如果有的话)并将其用作参考。我已经检查过是否有一个\使用过,在它之前找到一个空格后面跟着一个\,将上一个单词存储在列表中,然后在单词上插入一个订单号,以防单词上有许多类似的单词线。
Whe!结果是一个相当长的描述。有关应该如何完成的任何建议?另外,如果我的编码实践看起来很愚蠢,我很高兴知道。毕竟,毕竟还只是开始。 : - ]
在此先感谢!
预处理并重新插入它。尽可能多地思考,只是用一种笨拙的方法。 Muchas gracias! –