Skip to content
Advertisement

Replace all newline characters using python

I am trying to read a pdf using python and the content has many newline (crlf) characters. I tried removing them using below code:

from tika import parser

filename = 'myfile.pdf'
raw = parser.from_file(filename)
content = raw['content']
content = content.replace("rn", "")
print(content)

But the output remains unchanged. I tried using double backslashes also which didn’t fix the issue. can someone please advise?

Advertisement

Answer

I don’t have access to your pdf file, so I processed one on my system. I also don’t know if you need to remove all new lines or just double new lines. The code below remove double new lines, which makes the output more readable.

Please let me know if this works for your current needs.

from tika import parser

filename = 'myfile.pdf'

# Parse the PDF
parsedPDF = parser.from_file(filename)

# Extract the text content from the parsed PDF
pdf = parsedPDF["content"]

# Convert double newlines into single newlines
pdf = pdf.replace('nn', 'n')

#####################################
# Do something with the PDF
#####################################
print (pdf)
Advertisement