首页 > 解决方案 > TypeError:预期的字符串或类似字节的对象 Tqdm

问题描述

关于这个问题,我已经在 stackoverflow 中查看了几个来源,但无法解决。所以我把它贴在这里,请解决。

# Combining all the above statemennts 
from tqdm import tqdm
Other_skill = []
# tqdm is for printing the status bar
for sentance in tqdm(project_data['Other skills'].values):
    sent = decontracted(sentance)
    sent = sent.replace('\\r', ' ')
    sent = sent.replace('\\"', ' ')
    sent = sent.replace('\\n', ' ')
    sent = re.sub('[^A-Za-z0-9]+', ' ', sent)
    sent = ' '.join(e for e in sent.split() if e not in stopwords)
    Other_skill.append(sent.lower().strip())

错误:

TypeError                                 Traceback (most recent call last)
<ipython-input-12-30687b6f17e1> in <module>()
      4 # tqdm is for printing the status bar
      5 for sentance in tqdm(project_data['Other skills'].values):
----> 6     sent = decontracted(sentance)
      7     sent = sent.replace('\\r', ' ')
      8     sent = sent.replace('\\"', ' ')

<ipython-input-7-a344e4b38b78> in decontracted(phrase)
      4 def decontracted(phrase):
      5     # specific
----> 6     phrase = re.sub(r"won't", "will not", phrase)
      7     phrase = re.sub(r"can\'t", "can not", phrase)
      8 

C:\ProgramData\Anaconda3\lib\re.py in sub(pattern, repl, string, count, flags)
    189     a callable, it's passed the match object and must return
    190     a replacement string to be used."""
--> 191     return _compile(pattern, flags).sub(repl, string, count)
    192 
    193 def subn(pattern, repl, string, count=0, flags=0):

TypeError: expected string or bytes-like object

标签: pythonpython-3.x

解决方案


我认为 values() 中的括号是需要的。如果我是正确的 project_data 是字典,而您错过了值中的括号

from tqdm import tqdm
Other_skill = []
# tqdm is for printing the status bar 
# the values must have round brackets
for sentance in tqdm(project_data['Other skills'].values()):
    sent = decontracted(sentance)
    sent = sent.replace('\\r', ' ')
    sent = sent.replace('\\"', ' ')
    sent = sent.replace('\\n', ' ')
    sent = re.sub('[^A-Za-z0-9]+', ' ', sent)
    sent = ' '.join(e for e in sent.split() if e not in stopwords)
    Other_skill.append(sent.lower().strip())

推荐阅读