Как применить метод класса к столбцу pandas - PullRequest
0 голосов
/ 03 марта 2020

у меня есть куча твитов в столбце pandas. Я создал класс для обработки всех различных аспектов текста ie, удаления знаков препинания, расширения сокращений, удаления специальных символов и т. Д. c. Мне удалось обработать отдельные строки с помощью класса, однако я не могу понять, как применить методы ко всему столбцу текста.

class ProcessTweetText:
    def __init__(self, text):
        self.text = text

    def remove_web_link(self):
        self.text = re.sub(r"http\S+", "", self.text)
        return self.text

    def remove_html(self):
        self.text = self.text.replace('\n', ' ')
        return self.text

    def replace_contractions(self):
        return contractions.fix(self.text)

    def remove_hyphen(self):
        self.text = self.text.replace('—', ' ')
        self.text = self.text.replace('-', ' ')
        return self.text

    def remove_mentions(self):
        self.text = re.sub('@[A-Za-z0-9_]\S+', '', self.text)
        return self.text

    def remove_hashtags(self):
        self.text = re.sub('#[A-Za-z0-9_]\S+', '', self.text)
        return self.text

    def remove_punctuation(self):
        self.text = ''.join([c for c in self.text if c not in string.punctuation])
        return self.text

    def remove_special_characters(self):
        self.text = re.sub('[^a-zA-Z0-9 -]', '', self.text)
        return self.text

    def process_text(self):
        example.remove_web_link()
        example.remove_html()
        example.replace_contractions()
        example.remove_hyphen()
        example.remove_hyphen()
        example.remove_mentions()
        example.remove_hashtags()
        example.remove_punctuation()
        example.remove_special_characters()


example = ProcessTweetText(df['original_tweets'][100])
example.process_text()
example.text

Возможно, это не правильный путь к go по этому поводу, так как я все еще плохо знаком с использованием классов. Тем не менее, любая помощь в применении желаемых изменений в столбце pandas 'будет принята с благодарностью. Спасибо, ребята !!

1 Ответ

1 голос
/ 03 марта 2020

Если вы хотите сохранить свою структуру, вы можете использовать что-то вроде этого:

def foo(text):
    example = ProcessTweetText(text)
    example.process_text()
    return example.text

df['original_tweets'].apply(foo)

Но на самом деле я не вижу смысла в использовании класса для этой цели. Вы можете просто сделать это так:

def foo(text):
    text = re.sub(r"http\S+", "", text)
    text = text.replace('\n', ' ')
    text = text.replace('—', ' ')
    text = text.replace('-', ' ')
    text = re.sub('@[A-Za-z0-9_]\S+', '', text)
    text = re.sub('#[A-Za-z0-9_]\S+', '', text)
    text = ''.join([c for c in text if c not in string.punctuation])
    text = re.sub('[^a-zA-Z0-9 -]', '', text)
    return text

df['original_tweets'].apply(foo)
...