如何用白色 space 替换每个新行并用 python 中的白色 space 替换 2 个字符串?

How do i replace each new line with a whitespace and replace 2 strings with a white space in python?

这是在网站上抓取文章特定部分的答案。

soup.find("div", {"id": "content_wrapper"}).text

我应该用空格 (' ') 替换正文中的每个新行 ('\n')。我用 -soup.find("div", {"id": "content_wrapper"}).text.replace("\n", " ") 完成了这个。剥离()

但我仍然需要替换每个 '\xa0''\u200a' 字符串带有空格 (' ') 的正文并去除所有前导和尾随空格。

请问我该怎么做?

谢谢!

您可以在替换方法之后添加新的替换方法。

text = soup.find('div', {'id': 'content_wrapper'}).text
modified_text = text.replace('\n', ' ').replace('\xa0', ' ').replace('\u200a', ' ').strip()

如果我理解正确的话,您也想删除这些空格。那么,您不应该用空格“”替换单词。您应该将它们替换为空字符串“”。

text = soup.find('div', {'id': 'content_wrapper'}).text
modified_text = text.replace('\n', '').replace('\xa0', '').replace('\u200a', '').strip()

你需要做的就是检查它是否在文本中并覆盖它。 喜欢:

string = soup.find('div', {'id': 'content_wrapper'}).text
write = []
for i in string:
    if i.find('\xa0') == 0: i = ''
    if i.find('\u200a') == 0: i = ''
    write.append(i)