'python: apply all functions inside a class to a user input
I have a class and a some functions that changes the user input and saves it in a file as follows.
import os
import pandas as pd
from langdetect import detect
class Changer(object):
def __init__ (self, sent, id):
self.sent = sent
self.id = id
def panda_creator(self):
dic = {'text': [self.sent], 'id': [self.id]}
data = pd.DataFrame.from_dict(dic, orient='columns')
return data
def remove_punc(self, data):
data.text = data.text.str.replace('[^\w\s]', '', regex=True)
return data
def add_language(self, data):
data['lang'] = data.text.apply(detect)
return data
def save_data(self, data):
data.to_csv(os.path.join(os.getcwd(),'file.csv'))
def pars(sentence, id):
changer = Changer(sentence, id)
changer.panda_creator()
changer.remove_punc(changer.panda_creator())
changer.add_language(changer.remove_punc(changer.panda_creator()))
changer.save_data(changer.remove_punc(changer.panda_creator()))
if __name__== "__main__":
pars(input('sentence: '), input('id: '))
but the parse function only returns the loader function results and not the other functions' results. and even if it did, writing the functions inside other functions would not make sense if i had more functions. so is there a way of applying all functions on the user input in this class?
for example if user-input is : sentence: please, give me a glass of water. id: 23
I would expect the output in the file.csv to be:
,text,id,lang
0,please give me a glass of water,23,en
**note: **upadte posted as the answer based on the comments given.
Solution 1:[1]
Answer based on the comments in the question.
class Changer(object):
def __init__(self, sent, id):
self.sent = sent
self.id = id
def panda_creator(self):
dic = {'text': [self.sent], 'id': [self.id]}
data = pd.DataFrame.from_dict(dic, orient='columns')
self.remove_punc(data)
def remove_punc(self, data):
data.text = data.text.str.replace('[^\w\s]', '', regex=True)
self.add_language(data)
def add_language(self, data):
data['Lang_id'] = data.text.apply(detect)
self.save_data(data)
def save_data(self, data):
data.to_csv(os.path.join(os.getcwd(), 'file.csv'))
if __name__ == "__main__":
Changer(input('sentence: '), input('id: '))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | zara kolagar |