У меня эта ошибка, которая называется `'float', объект не повторяется`, даже после того, как я заменил все цифры в моем наборе данных пробелами - PullRequest
0 голосов
/ 01 июля 2019

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

Я пытался использовать регулярные выражения длязамените цифры пробелами.

import pandas as pd
import nltk
import re

df = pd.read_excel("samplefinal.xlsx")
df['comments'] = df['comments'].str.replace(r'\d+','')
mess = df["comments"]

from nltk.corpus import stopwords

def text_process(mess):
    nopunc = [char for char in mess if char not in string.punctuation]

    nopunc = ''.join(nopunc)

    return [word for word in nopunc.split() if word.lower() not in
    stopwords.words('english')]

df["comments"].apply(text_process)

данные:

    ID             Name                    comments

   28930           poil              The host canceled this reservation 24 
                                    days 
                                    before arrival. This is an automated 
                                    posting.

   7389             opil            This apartment is very clean and is 
                                    perfect for 2,  is 10 mins walking 
                                    from the Tabata 

сообщение об ошибке при использовании вышеуказанного кода: '' '

    TypeError                                 Traceback (most recent call 
    last)
    <ipython-input-22-ab6d2299296f> in <module>
    ----> 1 df["comments"].apply(text_process)

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

     pandas/_libs/lib.pyx in pandas._libs.lib.map_infer()

     <ipython-input-21-971b567ffb47> in text_process(mess)
           1 def text_process(mess):
     ----> 2  nopunc = [char for char in mess if char not in 
           string.punctuation]
           3 #nopunc = [char for char in mess if char not in 
           string.punctuation]
           4 nopunc = ''.join(nopunc)
           5 return [word for word in nopunc.split() if word.lower() not in 
            stopwords.words('english')]

            TypeError: 'float' object is not iterable

''' ожидание:

   ID             Name                    comments

   28930           poil             [host, canceled, reservation, 
                                    days,
                                    before, arrival, automated 
                                    posting

   7389             opil            [apartment,clean, 
                                    perfect, mins, walking 
                                    Tabata 

Я могу ошибаться с ожидаемым результатом, потому что я не знаю всех присутствующих стоп-слов, но я надеюсь, что вы поняли идею.Пожалуйста, помогите!

1 Ответ

0 голосов
/ 01 июля 2019

Я думаю, что это как-то связано с загрузкой ваших данных или с тем, как вы используете text_process, потому что, учитывая пример, который вы нам предоставили, ваш оригинальный код работает отлично.

Я пытался:

import pandas as pd
import string
from nltk.corpus import stopwords

df = pd.DataFrame({'ID': [28930, 7389], 'Name': ['poil', 'opil'], 'comments': [
    'The host canceled this reservation 24 days before arrival. This is an automated posting.',
    'This apartment is very clean and is perfect for 2,  is 10 mins walking from the Tabata']})

df['comments'] = df['comments'].str.replace(r'\d+', '')
mess = df["comments"]

from nltk.corpus import stopwords


def text_process(mess):
    nopunc = [char for char in mess if char not in string.punctuation]

    nopunc = ''.join(nopunc)

    return [word for word in nopunc.split() if word.lower() not in
            stopwords.words('english')]


print("DATA:")
print(df)

print("RESULTS:")
for row in mess:
    print(text_process(row))

и получил:

DATA:
      ID  Name                                           comments
0  28930  poil  The host canceled this reservation  days befor...
1   7389  opil  This apartment is very clean and is perfect fo...
RESULTS:
['host', 'canceled', 'reservation', 'days', 'arrival', 'automated', 'posting']
['apartment', 'clean', 'perfect', 'mins', 'walking', 'Tabata']

не могли бы вы добавить к вопросу код, который на самом деле вызывает text_process? может быть, вы как-то передаете строковый аргумент вместо строкового сообщения?

возможно, добавьте print(type(mess)) в качестве 1-й строки функции, чтобы увидеть, когда это float

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