I have read multiple posts regarding this error, but I still can’t figure it out. When I try to loop through my function:
JavaScript
x
17
17
1
def fix_Plan(location):
2
letters_only = re.sub("[^a-zA-Z]", # Search for all non-letters
3
" ", # Replace all non-letters with spaces
4
location) # Column and row to search
5
6
words = letters_only.lower().split()
7
stops = set(stopwords.words("english"))
8
meaningful_words = [w for w in words if not w in stops]
9
return (" ".join(meaningful_words))
10
11
col_Plan = fix_Plan(train["Plan"][0])
12
num_responses = train["Plan"].size
13
clean_Plan_responses = []
14
15
for i in range(0,num_responses):
16
clean_Plan_responses.append(fix_Plan(train["Plan"][i]))
17
Here is the error:
JavaScript
1
9
1
Traceback (most recent call last):
2
File "C:/Users/xxxxx/PycharmProjects/tronc/tronc2.py", line 48, in <module>
3
clean_Plan_responses.append(fix_Plan(train["Plan"][i]))
4
File "C:/Users/xxxxx/PycharmProjects/tronc/tronc2.py", line 22, in fix_Plan
5
location) # Column and row to search
6
File "C:UsersxxxxxAppDataLocalProgramsPythonPython36libre.py", line 191, in sub
7
return _compile(pattern, flags).sub(repl, string, count)
8
TypeError: expected string or bytes-like object
9
Advertisement
Answer
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
.
JavaScript
1
4
1
letters_only = re.sub("[^a-zA-Z]", # Search for all non-letters
2
" ", # Replace all non-letters with spaces
3
str(location))
4