簡體   English   中英

如何在Python輸出中從字典中包裝和縮進字符串?

[英]How can I wrap and indent strings from dictionary in Python output?

我需要幫助來包裝輸出文本。 我需要打印參考書,即書+章+詩號和實際詩句。 但是我需要換行以100個字符換行,然后與已打印的第一個部分對齊。

我有:

from operator import itemgetter

logfile = "kjv.txt"

def bible_read():
    fp=open(logfile,'r')
    store=[]
    while 1:

        line=fp.readline()

        if not line:
                    break
        if line[-1:] == '\n':
                    line=line[:-1]

        data0=line.split(' ')[0]
        data1=line.split(' | ')[1]
        data2=line.split('|')[2]
        store.append({'LINE':data0,'Chap':data1,'Verse':data2})
    fp.close()
    #print store[1]

    chapter = raw_input("Enter:")
    if '-' in chapter:
        book = chapter.split(" ")[0]
        w = chapter.split(":")[0]
        w = w.split(" ")[1]
        x = chapter.split(":")[1]
        x = x.split("-")[0]
        x = int(x)
        y = chapter.split("-")[1]
        y = int(y)
        #z = range[x,y]
        #print book, w, x, y
        chapR = range(x,y+1)
        for i in chapR:
            chapter = book + " " + w + ":" + str(i)
            record = next((item["Verse"] for item in store if item["Chap"] == chapter), None)
            print "%-10r %0r" % (chapter, record)


bible_read()

在這個部分:

        for i in chapR:
            chapter = book + " " + w + ":" + str(i)
            record = next((item["Verse"] for item in store if item["Chap"] == chapter), None)
            print "%-10r %0r" % (chapter, record)

我需要能夠打印出來:

'gen 1:2'  ' And the earth was without form, and void; and darkness was upon 
             the face of the deep. And the Spirit of God moved upon the face of
             the waters. '

所以我想得到100個字符的輸出換行然后縮進,所以它與原始縮進匹配。

日志文件的一部分:

2 | gen 1:3 | And God said, Let there be light: and there was light. 
3 | gen 1:4 | And God saw the light, that it was good: and God divided the light from the darkness. 
4 | gen 1:5 | And God called the light Day, and the darkness he called Night. And the evening and the morning were the first day. 
5 | gen 1:6 | And God said, Let there be a firmament in the midst of the waters, and let it divide the waters from the waters. 
6 | gen 1:7 | And God made the firmament, and divided the waters which were under the firmament from the waters which were above the firmament: and it was so. 
7 | gen 1:8 | And God called the firmament Heaven. And the evening and the morning were the second day.

使用textwrap模塊以特定的線寬包裝文本,並可選擇處理縮進。

要以某個寬度換行,然后添加自己的縮進,您可以使用:

from textwrap import wrap

wrapped_lines = wrap(record, 100)
indented_lines = ('\n' + ' ' * 11).join(wrapped_lines)

這會將您的record文本包裝為100個字符寬,然后縮小整個文本,除了第一行有11個空格; 你最終得到111個字符寬的文字。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM