首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用PyPdf2替换pdf中的文本

使用PyPdf2替换pdf中的文本
EN

Stack Overflow用户
提问于 2021-01-26 22:00:58
回答 1查看 210关注 0票数 0

我想用PyPdf2替换pdf中特定位置的文本。我试过这个:

代码语言:javascript
运行
复制
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)

但是我得到了一个错误:

代码语言:javascript
运行
复制
TypeError: 'str' object does not support item assignment

有什么办法可以解决这个问题吗?

谢谢,

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-01-26 22:06:26

使用replace()替换文本,例如:

代码语言:javascript
运行
复制
newTxt = txt.replace('#what word you want to repalce', '# which word you want to replace it with')

下面的代码将替换并保存文本文件:

代码语言:javascript
运行
复制
#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()
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65902765

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档