這裏完全初學者編碼器,在這個好地方首先發布。使用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! –