【问题标题】:TypeError: cannot use a bytes pattern on a string-like objectTypeError:不能在类似字符串的对象上使用字节模式
【发布时间】:2019-04-17 07:51:11
【问题描述】:

我正在尝试将一个句子标记为单词。在下面的代码中,我尝试使用一些预定义的拆分参数将句子拆分为单词。

import re
_WORD_SPLIT = re.compile(b"([.,!?\"':;)(])")

def basic_tokenizer(sentence):
    words = []
    for space_separated_fragment in sentence.strip().split():
        words.extend(_WORD_SPLIT.split(space_separated_fragment))
    return [w for w in words if w]

basic_tokenizer("I live, in Mumbai.")

它显示了一个错误:

TypeError: 不能在类似字符串的对象上使用字节模式。

之前这段代码对我来说可以正常工作,但是当我重新安装并安装 tensorflow 时,它显示了一个错误。我也使用了.decode() 函数,但它并没有解决我的问题。

我在 Ubuntu 上使用 python3.6。

【问题讨论】:

  • b"([.,!?\"':;)(])" -> r"([.,!?\"':;)(])"
  • 在下面查看我的答案,看看它是否对您有帮助!

标签: python regex python-3.x tokenize


【解决方案1】:

您在编译re 时给出了一个字节对象,而在调用它时您给出了一个字符串对象space_seprated_fragment

将其转换为字节,同时将其传递给_WORD_SPLIT

import re
_WORD_SPLIT = re.compile(b"([.,!?\"':;)(])")

def basic_tokenizer(sentence):
    words = []
    for space_separated_fragment in sentence.strip().split():
        words.extend(_WORD_SPLIT.split(space_separated_fragment.encode()))
    return [w for w in words if w]

basic_tokenizer("I live, in Mumbai.")

【讨论】:

  • 请注意,这会输出一个字节字符串列表:[b'I', b'live', b',', b'in', b'Mumbai', b'.']
【解决方案2】:

re.compile 采用普通字符串。 re.compile

import re
_WORD_SPLIT = re.compile("([.,!?\"':;)(])")

def basic_tokenizer(sentence):
    words = []
    for space_separated_fragment in sentence.strip().split():
        words.extend(_WORD_SPLIT.split(space_separated_fragment))
    return [w for w in words if w]
print(basic_tokenizer("I live, in Mumbai."))
#['I', 'live', ',', 'in', 'Mumbai', '.']

【讨论】:

    猜你喜欢
    • 2014-02-21
    • 2016-10-09
    • 1970-01-01
    • 1970-01-01
    • 2016-06-03
    • 2015-09-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多