【问题标题】:How to split line at non-printing ascii character in Python如何在 Python 中的非打印 ascii 字符处分割行
【发布时间】:2010-05-29 18:36:43
【问题描述】:

如何在 Python 中以非打印 ascii 字符(例如长减号十六进制 0x97 、八进制 227)分割一行? 我不需要角色本身。后面的信息会保存为变量。

【问题讨论】:

    标签: python split ascii extended-ascii


    【解决方案1】:

    您可以使用re.split

    >>> import re
    >>> re.split('\W+', 'Words, words, words.')
    ['Words', 'words', 'words', '']
    

    调整模式以仅包含您想要保留的字符。

    另见:stripping-non-printable-characters-from-a-string-in-python


    示例(带长减号):

    >>> # \xe2\x80\x93 represents a long dash (or long minus)
    >>> s = 'hello – world'
    >>> s
    'hello \xe2\x80\x93 world'
    >>> import re
    >>> re.split("\xe2\x80\x93", s)
    ['hello ', ' world']
    

    或者,与 unicode 相同:

    >>> # \u2013 represents a long dash, long minus or so called en-dash
    >>> s = u'hello – world'
    >>> s
    u'hello \u2013 world'
    >>> import re
    >>> re.split(u"\u2013", s)
    [u'hello ', u' world']
    

    【讨论】:

    • 我如何指定要在十六进制字符 97 处精确分割?
    • -1 (0) OP 有一个 EM DASH (U+2014, cp1252 x97),而不是一个 EN DASH (U+2013, cp1252 0x96)。 (1) 你的第二个例子是在 UTF-8 方面,显然 (??) OP 没有使用 (2) 使用 re.split 而不是 str.split 是严重的过度杀伤。
    【解决方案2】:
    _, _, your_result= your_input_string.partition('\x97')
    

    your_result= your_input_string.partition('\x97')[2]
    

    如果your_input_string 不包含'\x97',则your_result 将为空。如果your_input_string 包含多个 '\x97' 字符,则your_result 将包含第一个'\x97' 字符之后的所有内容,包括其他'\x97' 字符。

    【讨论】:

      【解决方案3】:

      只需使用字符串/unicode 拆分方法(他们并不真正关心您拆分的字符串(除了它是一个常量。如果您想使用正则表达式,请使用 re.split)

      要获得拆分字符串,要么像其他人展示的那样将其转义 "\x97"

      对字符串 (0-255) 使用 chr(0x97),对 unicode 使用 unichr(0x97)

      举个例子

      'will not be split'.split(chr(0x97))
      
      'will be split here:\x97 and this is the second string'.split(chr(0x97))
      

      【讨论】:

      • 谢谢。我喜欢 chr() 的使用。
      • (0) 你的意思是 str/unicode 拆分方法 (1) “除了它是一个常量”:它可以是任何计算为单个字符串的表达式(例如,chr(0x97) ) (2) 使用[uni]chr(0x97) instead of [u]"\x97" 是混淆/冗余/浪费/可弃用(恕我直言)——你会写float("1.23") 而不是1.23? (3) 如果在unicode中操作,他不需要unichr(0x97),他需要u"\u2014",即"\x97".decode("cp1252")
      • (0) 在我的 english 解释中,我真的必须指定它是 str 方法而不是对字符串进行操作的方法...哪个 str 类??? (1) 它是一个常量,指的是不能指定多个字符串的字符串(chr(97) 将始终为 '\x97'),其中 re.split 可以处理 '\x97|\x91'。 当然 你可以写 chr(i) 其中 i 是一个可以改变的变量。 (2) 是的...当然你不会进行浮点转换,但如果 chr 在运行时需要将数字转换为字符串,那么 chr 可能会很有用。
      • (3) 不,我没有检查 unicode 中的 0x97 是什么……我为什么要检查?他要了 0x97……我给了他。由他决定 ASCII 中的字符十六进制值与 unicode 中的不同(我只是表明存在 一个等价物会生成一个 unicode 字符串)
      • (0) 字符串是 str 类型或 unicode 类型的实例 (1) "constant" != "only one string" (3) 您不需要“检查 0x97 was in unicode" ... U+0080 到 U+009F 范围内的字符是 C1 控制字符,与破折号无关。如果你的 unicode 数据中有它们,你要么使用一些古老/神秘的协议 (prob=0.001),要么使用 latin1 而不是 cp1252 (prob=0.999) 解码。前 128 个 Unicode 字符故意与 ASCII 相同; “ASCII 中的字符十六进制值”不是“不同于 unicode 中的”。 0x97 不是 ASCII。
      猜你喜欢
      • 2010-12-14
      • 1970-01-01
      • 1970-01-01
      • 2012-10-14
      • 1970-01-01
      • 2021-05-21
      • 1970-01-01
      • 2013-03-29
      • 2013-11-19
      相关资源
      最近更新 更多