使用 python 替换所有换行符

Len*_*eni 9 python python-3.x

我正在尝试使用 python 阅读 pdf,内容有许多换行符 (crlf)。我尝试使用下面的代码删除它们:

from tika import parser

filename = 'myfile.pdf'
raw = parser.from_file(filename)
content = raw['content']
content = content.replace("\r\n", "")
print(content)
Run Code Online (Sandbox Code Playgroud)

但输出保持不变。我尝试使用双反斜杠也没有解决问题。有人可以建议吗?

Alb*_*ert 15

content = content.replace("\\r\\n", "")
Run Code Online (Sandbox Code Playgroud)

你需要双重逃脱他们。

  • 为了确保所有情况(Windows 或 unix ascii 字符串),请使用 `content = content.replace("\r", "").replace("\n", "")` (9认同)
  • 您不需要转义“\r\n”,因为它们已经是有效的字符文字。 (8认同)

Lif*_*lex 3

我无法访问您的 pdf 文件,因此我在我的系统上处理了一份。我也不知道您是否需要删除所有新行或只是删除两个新行。下面的代码删除了双新行,这使得输出更具可读性。

请告诉我这是否适合您当前的需求。

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('\n\n', '\n')

#####################################
# Do something with the PDF
#####################################
print (pdf)
Run Code Online (Sandbox Code Playgroud)