【问题标题】:How to replace all ` ` with a space in an html file?如何用 html 文件中的空格替换所有` `?
【发布时间】:2019-08-20 22:12:12
【问题描述】:

我想用 html 文件文本部分中的空格字符替换所有   字符(或任何变体,如    )。 (即text_content()lxml 中返回的那些。不应更改属性等任何其他内容。)

这样的事情不能保证只改变文本部分。

Replace `\n` in html page with space in python LXML

在 lxml 中这样做的正确方法是什么?

【问题讨论】:

  • 听起来你应该取一个字符串,然后用空格替换所有正则表达式?
  • 问题是如何迭代所有元素并替换每个元素的文本。
  • 在将此文本与lxml一起使用之前使用text = text.replace(" ", " ").replace(" ", " ")
  • 如何迭代所有文本?
  • 在使用lxml之前从文件或页面读取文本并替换它 - 您将只有一个文本可以更改它,无需迭代。

标签: python html lxml


【解决方案1】:

您可以使用正则表达式的替换来替换子字符串

import re
text = '''
I'd like to replace all   characters (or any variants like    ) by a 
space character in the text part of an html file. (i.e., the 
ones returned by text_content() in lxml. 
Things in anything else like attributes should not be changed.)
'''
out = re.sub(r"&\S*;", r"", text)
print(out)

>>I'd like to replace all  characters (or any variants like  ) by a 
space character in the text part of an html file. (i.e., the ones returned by text_content() in lxml. 
Things in anything else like attributes should not be changed.)

【讨论】:

  • 这和另一个答案有同样的问题。
  • 然后使用 HTML2Text python 库来解析 HTML 的文本组件。获取文本正文,使用RegEx替换&\S*;然后在 HTML 中替换这些新的文本正文
【解决方案2】:

您可以使用open() 函数读取文件并将它们附加到变量中。然后,您可以替换某些并将其写回文件。这是一个例子:

#My File
myFile = 'myFile.html'

#Read the file and gather the contents
with open(myFile, "r") as f:
    contents = f.read()
    print(contents)

#What we want to replace unwanted contents with
newContents = contents.replace(' ', ' ')

#Now write the file with the contents you want
with open(myFile, 'w') as f:
    f.write(newContents)
    print(newContents)

【讨论】:

  • 我只需要替换文本而不是其他任何内容。这不能保证不改变属性之类的其他东西。
  • @user1424739 你真的有' ' 属性吗?也许你提出了不存在的问题。
  • @user1424739 你有任何带有   的属性吗?在他们中?如果不是,我认为这是一个合适的答案。
  • 不知道有没有包含&#160的HTML文件。要知道它,我必须检查每个输入文件,这是我做不到的。因此,我不想做出这样的假设。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-01-14
  • 2011-10-06
  • 1970-01-01
  • 2018-04-15
  • 1970-01-01
  • 2018-11-23
  • 2021-03-11
相关资源
最近更新 更多