python使用textwrap包在已经生成的长字符串中嵌入回车符实战
Posted Data+Science+Insight
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python使用textwrap包在已经生成的长字符串中嵌入回车符实战相关的知识,希望对你有一定的参考价值。
python使用textwrap包在已经生成的长字符串中嵌入回车符实战
目录
python使用textwrap包在已经生成的长字符串中嵌入回车符实战
有一个非常长的string字符串,我们需要写入到pdf或者word中,需要在字符串中加入换行符号,如何实施?
使用textwrap包;
# textwrap包在长字符串中嵌入回车符
import textwrap
strs = "In my project, I have a bunch of strings that are read in from a file. Most of them, when printed in the command console, exceed 80 characters in length and wrap around, looking ugly."
print(textwrap.fill(strs, 20))
In my project, I
have a bunch of
strings that are
read in from a file.
Most of them, when
printed in the
command console,
exceed 80 characters
in length and wrap
around, looking
ugly.
#实战将多行文本写入pdf
pdftext = json.dumps(result_values)
pdftext
import textwrap
print(textwrap.fill(pdftext, 100))
file = "test.txt"
with open(file, 'w') as f:
f.write(textwrap.fill(pdftext, 100))
with open(file, 'r') as f:
lines = f.readlines()
# lines
for line in lines:
pass
#
from fpdf import FPDF
from PIL import Image
import os
def makePdf(pdfFileName, listPages):
cover = Image.open(listPages[0])
width, height = cover.size
#pdf = FPDF(unit = "pt", format = [width, height])
pdf = FPDF(unit = "mm",format = [width, height])
ratio = height/width
#print(ratio)
for page in listPages:
pdf.add_page()
pdf.image(page, 0, 0,w=width,h=height)
pdf.add_page()
pdf.set_font('Arial', 'B', 14)
#pdf.text(0, 0, str(pdftext))
for index,line in enumerate(lines):
y = (index+1)*20
pdf.cell(0, y, line)
#pdf.text(10, 10, pdftext)
pdf.output(pdfFileName, "F")
# makePdf("result.pdf", [imgFileName for imgFileName in os.listdir('.') \\
# if imgFileName.endswith("png")])
makePdf(str(timestamp) +"graph.pdf", [imgFileName for imgFileName in final_filelist])
参考:A good way to make long strings wrap to newline?https://stackoverflow.com/questions/16430200/a-good-way-to-make-long-strings-wrap-to-newline
参考: Python File I/O | How to read write files in Python
以上是关于python使用textwrap包在已经生成的长字符串中嵌入回车符实战的主要内容,如果未能解决你的问题,请参考以下文章