【问题标题】:Python - Check multiple white spaces in stringPython - 检查字符串中的多个空格
【发布时间】:2018-03-03 18:42:50
【问题描述】:

我正在使用这个函数来检查一个字符串是否包含多个空格:

def check_multiple_white_spaces(text):
    return "  " in text

它通常工作正常,但在以下代码中却没有:

from bs4 import BeautifulSoup
from string import punctuation

text = "<p>Hello &nbsp; &nbsp; &nbsp;world!!</p>\r\n\r"

text = BeautifulSoup(text, 'html.parser').text
text = ''.join(ch for ch in text if ch not in set(punctuation))
text = text.lower().replace('\n', ' ').replace('\t', '').replace('\r', '')

print check_multiple_white_spaces(text)

text 变量的最终值为hello      world,但我不知道为什么check_multiple_white_spaces 函数返回的是False 而不是True

我该如何解决这个问题?

【问题讨论】:

  • 看看print(repr(text)) 显示的内容......在你喝完汤之后

标签: python string python-2.7 beautifulsoup whitespace


【解决方案1】:

如果您要使用repr() 打印text 的内容,您会看到它不包含两个连续的空格:

'hello \xa0 \xa0 \xa0world '

因此,您的函数正确返回 False。这可以通过将不间断空格转换为空格来解决:

text = text.replace(u'\xa0', u' ')

【讨论】:

    【解决方案2】:

    首先,您的函数check_multiple_white_spaces 无法真正检查是否有多个空格,因为可能有三个或更多空格。

    你应该使用re.search(r"\s{2,}", text)

    其次,如果你打印text,你会发现你需要对文本进行转义。

    查看这个答案。

    How do I unescape HTML entities in a string in Python 3.1?

    【讨论】:

    • 这是 Python 2.x 的问题。您需要将re.UNICODE 传递给re.search 方法以匹配所有Unicode 空白字符与\s
    • @WiktorStribiżew 你是对的,我已经迁移到 python3 很长时间了。很抱歉。
    【解决方案3】:

    text变量中没有连续的空格,这就是check_multiple_white_spaces函数返回False值的原因。

    >>> text
    u'hello \xa0 \xa0 \xa0world '
    >>> print text
    hello      world 
    

    \xa0 是不间断空间、不可破坏空间 (NBSP)、硬空间。 os space的值为32,non-break space的值为160

    (u' ', 32)
    (u'\xa0', 160)
    

    字符 \xa0 是一个 NO-BREAK SPACE,最接近的 ASCII 等价物当然是一个常规空格。

    使用 unidecode module 将所有非 ASCII 字符转换为其最接近的 ASCII 等效字符

    演示:

    >>> import unidecode
    >>> unidecode.unidecode(text)
    'hello      world '
    >>> "  " in unidecode.unidecode(text)
    True
    

    【讨论】:

      猜你喜欢
      • 2014-06-23
      • 2015-06-02
      • 1970-01-01
      • 2015-05-29
      • 1970-01-01
      • 2021-12-07
      • 2022-07-13
      • 2013-02-04
      • 1970-01-01
      相关资源
      最近更新 更多