【问题标题】:Error while assigning function to the values of a dictionary将函数分配给字典的值时出错
【发布时间】:2018-08-03 12:20:18
【问题描述】:

我正在尝试使用以下命令为我的 dict 的值分配一个函数:

x_text = [clean_str(v) for k, v in answer.items()]

函数 clean_str:

def clean_str(string):
    # remove stopwords
    # string = ' '.join([word for word in string.split() if word not in cachedStopWords])
    string = re.sub(r"[^A-Za-z0-9(),!?\'\`]", " ", string)
    string = re.sub(r"\'s", " \'s", string)
    string = re.sub(r"\'ve", " \'ve", string)
    string = re.sub(r"n\'t", " n\'t", string)
    string = re.sub(r"\'re", " \'re", string)
    string = re.sub(r"\'d", " \'d", string)
    string = re.sub(r"\'ll", " \'ll", string)
    string = re.sub(r",", " , ", string)
    string = re.sub(r"!", " ! ", string)
    string = re.sub(r"\(", " \( ", string)
    string = re.sub(r"\)", " \) ", string)
    string = re.sub(r"\?", " \? ", string)
    string = re.sub(r"\s{2,}", " ", string)
    return string.strip().lower()

但我收到以下错误:

文件“C:\ProgramData\Anaconda3\lib\re.py”,第 191 行,在 sub return _compile(pattern, flags).sub(repl, string, count)

TypeError:预期的字符串或类似字节的对象

我的 dict(answer{}) 的前 2 k,v 对的 sn-p 如下:

In[45]:{k: answer[k] for k in list(answer)[:2]}
Out[45]: 
{b'B00308CJ12': [b'Bulletproof Salesman (2008)'],
 b'189138922X': [b'Classical Mechanics']} 

【问题讨论】:

  • 请出示clean_str()的代码。
  • 编辑过的原qn...

标签: string python-3.x function dictionary text


【解决方案1】:

你的dict的值都是字节而不是字符串,re.sub只能处理字符串。

您应该使用decode() 方法将字节转换为字符串:

x_text = [clean_str(i.decode()) for k, v in answer.items() for i in v]

【讨论】:

  • >>error:'list' object has no attribute 'decode'
  • 我明白了。如果它只有一个项目,不确定为什么你的值是一个列表,但你总是可以在列表推导中使用另一个 for 循环来提取其中的值。我已经相应地更新了我的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-08
  • 2021-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-27
相关资源
最近更新 更多