预期的字符串或字节对象

时间:2021-12-26 20:10:31

I have read multiple posts regarding this error, but I still can't figure it out. When I try to loop through my function:

我已阅读有关此错误的多篇帖子,但我仍然无法弄明白。当我尝试循环我的函数时:

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]))

Here is the error:

这是错误:

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

1 个解决方案

#1


10  

As you stated in the comments, some of the values appeared to be floats, not strings. You will need to change it to strings before passing it to re.sub. The simplest way is to change location to str(location) when using re.sub. It wouldn't hurt to do it anyways even if it's already a str.

正如你在评论中所说,一些值似乎是浮点数,而不是字符串。在将其传递给re.sub之前,您需要将其更改为字符串。最简单的方法是在使用re.sub时将位置更改为str(位置)。即使它已经是一个str,它也不会受到影响。

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

#1


10  

As you stated in the comments, some of the values appeared to be floats, not strings. You will need to change it to strings before passing it to re.sub. The simplest way is to change location to str(location) when using re.sub. It wouldn't hurt to do it anyways even if it's already a str.

正如你在评论中所说,一些值似乎是浮点数,而不是字符串。在将其传递给re.sub之前,您需要将其更改为字符串。最简单的方法是在使用re.sub时将位置更改为str(位置)。即使它已经是一个str,它也不会受到影响。

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