re.sub 出现“预期的字符串或类似字节的对象”错误

新手上路,请多包涵

我已经阅读了有关此错误的多个帖子,但我仍然无法弄清楚。当我尝试遍历我的函数时:

 def fix_Plan(location):
    letters_only = re.sub("[^a-zA-Z]",  # Search for all non-letters
                          " ",          # Replace all non-letters with spaces
                          location)     # Column and row to search

    words = letters_only.lower().split()
    stops = set(stopwords.words("english"))
    meaningful_words = [w for w in words if not w in stops]
    return (" ".join(meaningful_words))

col_Plan = fix_Plan(train["Plan"][0])
num_responses = train["Plan"].size
clean_Plan_responses = []

for i in range(0,num_responses):
    clean_Plan_responses.append(fix_Plan(train["Plan"][i]))

这是错误:

 Traceback (most recent call last):
  File "C:/Users/xxxxx/PycharmProjects/tronc/tronc2.py", line 48, in <module>
    clean_Plan_responses.append(fix_Plan(train["Plan"][i]))
  File "C:/Users/xxxxx/PycharmProjects/tronc/tronc2.py", line 22, in fix_Plan
    location)  # Column and row to search
  File "C:\Users\xxxxx\AppData\Local\Programs\Python\Python36\lib\re.py", line 191, in sub
    return _compile(pattern, flags).sub(repl, string, count)
TypeError: expected string or bytes-like object

原文由 imanexcelnoob 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 831
2 个回答

正如您在评论中所说,一些值似乎是浮点数,而不是字符串。在将其传递给 re.sub 之前,您需要将其更改为字符串。最简单的方法是在使用 str(location) 时将 location 更改为 --- re.sub 。即使它已经是 str ,无论如何这样做也没有什么坏处。

 letters_only = re.sub("[^a-zA-Z]",  # Search for all non-letters
                          " ",          # Replace all non-letters with spaces
                          str(location))

原文由 Taku 发布,翻译遵循 CC BY-SA 3.0 许可协议

最简单的解决方案是将 Python str 函数应用到您尝试循环的列。

如果您使用的是 pandas ,这可以实现为:

 dataframe['column_name']=dataframe['column_name'].apply(str)

原文由 msaif 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题