关于python:re.sub错误与“预期的字符串或字节类对象”

re.sub erroring with “Expected string or bytes-like object”

我已经阅读了多篇关于这个错误的文章,但我仍然无法理解。当我试图循环我的函数时:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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]))

错误如下:

1
2
3
4
5
6
7
8
9
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
e.py"
, line 191, in sub
    return _compile(pattern, flags).sub(repl, string, count)
TypeError: expected string or bytes-like object


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

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