我想用PyPdf2替换pdf中特定位置的文本。我试过这个:
import PyPDF2 as pdf
filename = 'C:/Users/Workstation/Downloads/Sample Text.pdf'
Report = open(filename, 'rb')
pdfReader = pdf.PdfFileReader(Report)
pageObj = pdfReader.getPage(0)
txt = pageObj.extractText()
name = txt[34]
print("name: "+name)
txt[72:80] = "solarsys" #Replacement of text
star_sys = txt[71:83]
print("star_system: "+star_sys)
但是我得到了一个错误:
TypeError: 'str' object does not support item assignment
有什么办法可以解决这个问题吗?
谢谢,
发布于 2021-01-26 22:06:26
使用replace()
替换文本,例如:
newTxt = txt.replace('#what word you want to repalce', '# which word you want to replace it with')
下面的代码将替换并保存文本文件:
#input file
test = open("Test.txt", "w+")
#output file to write the result to
test2 = open("Test2.txt", "wt")
#for each line in the input file
for line in test:
#read replace the string and write to output file
test2.write(line.replace('replace', 'replaced'))
#close input and output files
test.close()
test2.close()
https://stackoverflow.com/questions/65902765
复制相似问题