gpt4 book ai didi

python - 如何在 Python 输出中换行和缩进字典中的字符串?

转载 作者:行者123 更新时间:2023-11-30 23:34:51 25 4
gpt4 key购买 nike

我需要帮助来包装我的输出文本。我需要打印引用文献,即书+章节+诗句编号和实际诗句。但是,我需要该行以 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 module以一定的线宽换行文本,并可选择处理缩进。

要以一定的宽度换行,然后添加您自己的缩进,您可以使用:

from textwrap import wrap

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

这会将您的 record 文本换行为 100 个字符宽,然后将除第一行之外的整个文本缩进 11 个空格;您最终得到的文本宽度为 111 个字符。

关于python - 如何在 Python 输出中换行和缩进字典中的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17862989/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com