代码之家  ›  专栏  ›  技术社区  ›  Emy

在python中,如何用空格替换每一行,用空格替换两个字符串?

  •  0
  • Emy  · 技术社区  · 2 年前

    这是一个在网站上搜刮文章某个特定部分的答案。

    汤查找(“div”,“id”:“content_wrapper”})。文本

    我应该用空格(“”)替换正文中的每一行(“\n”)。我是用汤做的。查找(“div”,“id”:“content_wrapper”})。文本替换(“\n”,”)。strip()

    但我还是需要 更换每个 “\xa0” “\u200a” 在正文文本中使用空格(“”)并去掉所有前导和尾随空格。

    我该怎么做?

    非常感谢。

    2 回复  |  直到 2 年前
        1
  •  0
  •   f1nch    2 年前

    只需在替换方法之后添加新的替换方法即可。

    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()
    
        2
  •  0
  •   thenoob ofsome number of noobs    2 年前

    你所需要做的就是检查它是否在文本中,然后把它写下来。 比如:

    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)