Ошибка: ожидаемая строка или байтовоподобный объект - PullRequest
0 голосов
/ 14 декабря 2018

Я работаю над предварительной обработкой данных для столбца «Описание работы», который содержит текстовый формат данных.Я создал фрейм данных и пытаюсь применить функцию для предварительной обработки данных, но получаю ошибку как «ожидаемая строка или байтовоподобный объект» при применении функции к столбцу в фрейме данных.Пожалуйста, используйте мой код ниже и помогите.

####################################################    
#Function to pre process the data    
def clean_text(text):
        """
        Applies some pre-processing on the given text.

        Steps :
        - Removing HTML tags
        - Removing punctuation
        - Lowering text
        """

        # remove HTML tags
        text = re.sub(r'<.*?>', '', text)

        # remove the characters [\], ['] and ["]
        text = re.sub(r"\\", "", text)    
        text = re.sub(r"\'", "", text)    
        text = re.sub(r"\"", "", text)    

        # convert text to lowercase
        text = text.strip().lower()

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

        # replace punctuation characters with spaces
        filters='!"\'#$%&()*+,-./:;<=>?@[\\]^_`{|}~\t\n'
        translate_dict = dict((c, " ") for c in filters)
        translate_map = str.maketrans(translate_dict)
        text = text.translate(translate_map)

        return text
#############################################################     
#To apply "Clean_text" function to job_description column in data frame        
df['jobnew']=df['job_description'].apply(clean_text)
        ---------------------------------------------------------------------------
        TypeError                                 Traceback (most recent call last)
        <ipython-input-33-c15402ac31ba> in <module>()
        ----> 1 df['jobnew']=df['job_description'].apply(clean_text)

        ~\Anaconda3\lib\site-packages\pandas\core\series.py in apply(self, func, convert_dtype, args, **kwds)
           3192             else:
           3193                 values = self.astype(object).values
        -> 3194                 mapped = lib.map_infer(values, f, convert=convert_dtype)
           3195 
           3196         if len(mapped) and isinstance(mapped[0], Series):

        pandas/_libs/src\inference.pyx in pandas._libs.lib.map_infer()

        <ipython-input-30-5f24dbf9d559> in clean_text(text)
             10 
             11     # remove HTML tags
        ---> 12     text = re.sub(r'<.*?>', '', text)
             13 
             14     # remove the characters [\], ['] and ["]

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

        TypeError: expected string or bytes-like object

1 Ответ

0 голосов
/ 15 декабря 2018

Функция re.sub сообщает вам, что вы вызвали ее с чем-то (аргумент text), который не является строкой.Поскольку он вызывается путем вызова apply для содержимого df['job_description'], очевидно, что проблема заключается в том, как вы создали этот фрейм данных ... и вы не показываете эту часть своего кода.

Создайте свой фрейм данных таким образом, чтобы в этом столбце содержались только строки, и ваша программа работала без ошибок как минимум еще на несколько строк.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...