I have this big output. Everytime that the url appears, the number below the url is the ID (and its important), and also if the url appears at the output is one request to the api
The preview of the output :
https://xxxxxx/api/v1/implantacao/projeto/254/tarefa?start=0&limit=50
254
INFORME DE FRANQUIA VENDIDA
T01
1
PONTO COMERCIAL
CONTRATO DE LOCAÇÃO ASSINADO
T04
1
PONTO COMERCIAL
INTEGRAÇÃO: TIMELINE | ACESSOS
T05
1
TIMELINE
E-MAIL: CRIAR E-MAILS
T144
1
TIMELINE
ACESSOS SULTS: CRIAR ACESSOS
T145
1
TIMELINE
PRECIFICAÇÃO: ANÁLISE DE MARGEM E MARK-UP
T142
2
MIX INICIAL
VETERINÁRIO: PERÍODO DE SELEÇÃO DE CLÍNICO GERAL
T86
2
VETERINÁRIO
ESPECIALISTAS: PESQUISA POR PROFISSIONAIS
T157
2
DRA. MEI
TREINAMENTO: VESTINDO A CAMISA (PRESENCIAL)
T91
2
That part of the code :
def unidades(data):
for i in data['data']:
name = (i['nome'])
codigo = (i['codigo'])
situation = (i['situacao'])
subName = (i['fase']['nome'])
How can i print this into excel, using xlwt ?
I tried :
line = 0
for i in data['data']:
name = (i['nome'])
sheet.write(1, line, name)
linha += 1
But this code above didn't worked, only printed 7 itens in my excel file
Related
I trying to make a whatsapp bot which returns a response for specifics messages
#app.route("/sms", methods=['POST'])
def sms_reply():
# Fetch the message
msg = request.form.get('Body').lower()
responded = False
if ("hola" in msg or "buenos" in msg or "buenas" in msg or "info" in msg or "holi" in msg):
reply = "Buenos días bienvenido a Alcanza soy tu asistente virtual, ¿con quien tengo el gusto?"
menu = "Por Favor, selecciona la opcion de tu preferencia: 1 Citas con asesores 2 Informacion de servicios 3 Herramientas de diagnostico 4 Servicio al cliente"
resp = MessagingResponse()
resp.message(reply)
resp.message(menu)
elif ("1" in msg):
reply = "Bienvenido al menu de citas con asesores, por favor selecciona una opcion: 1 Agendar una cita 2 Modificar una existente 3Cancelar una cita 0 Volver al menú principal"
resp = MessagingResponse()
resp.message(reply)
elif ("2" in msg):
reply = "Bienvenido al menu de informacion de servicios, por favor seleciona un servicio para recibir mas informacion: Finanzas personales 1 Asesoría de inversión 2 Webinars y capacitaciones 3 Alcanza 360 0 Volver al menú principal"
resp = MessagingResponse()
resp.message(reply)
elif ("3" in msg):
reply = "Bienvenido al menu de herramientas de diagnostico, por favor seleciona la herramienta que necesitas: 1 Cuestionario de diagnóstico financiero 2 Perfil de deuda 3 Perfil de inversión 4 Costo de tu tiempo 5 Pago de tarjeta de crédito 6 Volver al menú principal"
resp = MessagingResponse()
resp.message(reply)
return str(resp)
So I create this function and when I get the input message "1" from whatsapp the code return me a sub menu, the point is that I want to add another if statement into de principal ifs with more options, for example first input== "1" return (sub menu) and first input == "1" and second input == "1" return (option 1 of the sub menu), I tried too many times and different ifs but the code stops working or ignore the sub ifs
I´m trying to remove rows containing blank texts or in tweet texts column. But I have tried in different ways counting the rows that only contain whitespace or counting the leading spaces and trailing spaces but to get a criterion to eliminate it.
ID tweet WhiteSpaceCount HaveWhiteSpace
0 this is a text 0 False
1 0 False
2 Hello im fine 0 False
I want to delete all the rows that don´t have any information on the tweet column.
Code here:
def extractAndSave(api, name):
# Creamos una lista de tweets:
previous_date = date.today() - timedelta(days=1)
query_date = date.today()
name = name
tweets = API_EXTRACTOR.search(q=name + "-filter:retweets", result_type='recent', timeout=999999, count=200,
end_time=previous_date, tweet_mode='extended')
# Podemos crear un dataframe como sigue:
tweet_list = []
for tweet in tweets:
tweet_list.append(tweet.full_text)
datos = pd.DataFrame(data=tweet_list, columns=['TWEETS'])
# CREANDO COLUMNA DE ID
id_list = []
for id in tweets:
id_list.append(id.id)
id = pd.DataFrame(data=id_list, columns=['ID'])
# CREANDO COLUMNA DE ID
creado_list = []
for creado in tweets:
creado_list.append(creado.created_at)
creado = pd.DataFrame(data=creado_list, columns=['FECHA_CREACION'])
# CREANDO COLUMNA DE nombre de usuario
user_list = []
for usuario in tweets:
user_list.append(usuario.user.screen_name)
usuario = pd.DataFrame(data=user_list, columns=['USUARIO'])
# CREANDO COLUMNA DE FUENTE
fuente_list = []
for fuente in tweets:
fuente_list.append(fuente.source)
fuente = pd.DataFrame(data=fuente_list, columns=['FUENTE'])
# CREANDO COLUMNA DE ME GUSTA
like_list = []
for like in tweets:
like_list.append(like.favorite_count)
like = pd.DataFrame(data=like_list, columns=['ME_GUSTA'])
# CREANDO COLUMNA DE RT
rt_list = []
for rt in tweets:
rt_list.append(rt.retweet_count)
retweet = pd.DataFrame(data=rt_list, columns=['ME_GUSTA'])
# CREANDO COLUMNA DE IDIOMA
idioma_list = []
for idioma in tweets:
idioma_list.append(idioma.lang)
idioma = pd.DataFrame(data=idioma_list, columns=['IDIOMA'])
# CREANDO COLUMNA DE IDIOMA
quote_list = []
for quote in tweets:
quote_list.append(quote.is_quote_status)
quote = pd.DataFrame(data=quote_list, columns=['CITADO'])
# CREANDO COLUMNA DE IDIOMA
location_list = []
for location in tweets:
location_list.append(location.user.location)
location = pd.DataFrame(data=location_list, columns=['LOCACION'])
# CONCATENANDO DATAFRAMES
datos = pd.concat([datos, id, creado, usuario, fuente, like, retweet, quote, idioma, location], axis=1)
# Dropear toda la fila si la columna tweets viene vacia.
datos['pass/fail'] = np.where(datos['TWEETS'].astype(str).str.fullmatch(r"\s*"),'FAIL','PASS')
datos['CONTEO_ESPACIOS']= (datos['TWEETS'].str.startswith(" ") | datos['TWEETS'].str.endswith(" ")).sum()
# Hora de publicación
datos['HORA_PUBLICACION'] = datos['FECHA_CREACION'].dt.hour
datos['DIA_SEMANA'] = datos['FECHA_CREACION'].dt.day_name()
# Extrayendo solo los tweets del día anterior
datos['FECHA_CREACION'] = pd.to_datetime(datos['FECHA_CREACION']).dt.date
datos = datos[datos['FECHA_CREACION'] == previous_date]
print(datos)
# Guardando en dataframe.
return datos
Instead of removing rows that you don't need, keep only the ones you do need:
df = df[df["tweet"].str.strip().str.len()>0]
>>> df
ID tweet WhiteSpaceCount HaveWhiteSpace
0 0 this is a text 0 False
2 2 Hello im fine 0 False
I'm trying to add to the Table Widget the information that I have on my SQLite table.
That's it my SQL table:
.
That my Table Widget:
The code of the method:
if self.ui.btn_jugadores.clicked.connect(lambda: self.ui.pila_de_paginas.setCurrentWidget(self.ui.pg_jugadores)): self.mostrar_jugadores()
def mostrar_jugadores(self):
try:
cursor = conectarse_bbdd_jugadores()
consulta = ''' SELECT * FROM jugadores'''
ejecucion = cursor.execute(consulta).fetchall()
if len(ejecucion) > 0:
fila = 0
for e in ejecucion:
columna = 0
for apartado in e:
celda = QTableWidgetItem(apartado)
self.ui.tabla_jgds.setItem(fila, columna, celda)
columna += 1
print(apartado)
fila += 1
else:
QMessageBox.setText('No hay registros en la tabla de jugadores')
QMessageBox.setIcon(QMessageBox.warning)
QMessageBox.exec_()
except Error as error:
QMessageBox.setText('No se ha podido ejecutar la sentencia')
QMessageBox.setIcon(QMessageBox.warning)
QMessageBox.exec_()
And this is the result:
when I executed it
I don't know why the numbers are not appearing in the table widget.
I use the twilio API to write a simple program to remember my father to take his meds. Here is my code which can be replicated by anyone who has an account in twilio, one phone number and the sheet medications.csv(see bellow):
from twilio.rest import Client
import pandas as pd
from datetime import datetime
import re
account_sid = 'XXXXXXXXXXXXX' #INSERT YOUR SID HERE
auth_token = 'XXXXXXXXXXXXX' #INSERT YOUR TOKEN HERE
client = Client(account_sid, auth_token)
def to_list_integer(dt_time):
return [dt_time.year,dt_time.month,dt_time.day, dt_time.hour,dt_time.minute]
df=pd.read_csv('medications.csv')
while True:
data_lista = to_list_integer(datetime.now())
x=datetime(*data_lista)
hora = x.strftime("%Hh%M")
for i in range(len(df)):
if (datetime.now().hour==df['hour'][i]) & (datetime.now().minute==df['minute'][i]) & (datetime.now().second==1):
text = '''*Lembrete: {0}*\n
Olá sr. X, agora são {1},
\nestá na hora de tomar {2} comprimido(s) de {0}
\n\n*recomendação médica: {3}*'''.format(df['name'][i],hora,re.search(r'\d+',df['recomendation'][i]).group(),
df['recomendation'][i])
persons=['whatsapp:+XXXXXXXXXXXXX','whatsapp:+XXXXXXXXXXXXX','whatsapp:+XXXXXXXXXXXXX',
'whatsapp:+XXXXXXXXXXXXX', 'whatsapp:+XXXXXXXXXXXXX']
for person in persons:
message = client.messages.create(
body=text,
from_='whatsapp:+XXXXXXXXXXX',#INSERT YOUR TWILIO NUMBER HERE
to=person
)
print(message.sid)
medications.csv:
name,dosage,recomendation,hour,minute
Selozek,100mg,Tomar 1 comprimido pela manhã,6,9
Vasopril Plus,20/12.5 mg,Tomar 1 comprimido pela manhã,6,10
Glifage XR,500mg,Tomar 2 comprimidos após o café e após a última refeição da noite,7,10
Clopidogrel,75mg,Tomar 1 comprimido após o almoço,13,10
AAS,100mg,Tomar 1 comprimido após o almoço,13,11
Enalapril,10mg,Tomar 2 comprimidos à noite,20,10
Glifage XR,500mg,Tomar 2 comprimidos após o café e após a última refeição da noite,20,11
Rosuvastatina,20mg,Tomar 1 comprimido após a última refeição da noite,20,12
The code was working properly yesterday but today it is no longer working. The program runs without errors and print the sids for each message. However, none of the phones in the list persons are receiving the message. What is wrong here?
I am importing an excel worksheet that has the following columns name:
N° Pedido
1234
6424
4563
The column name ha a special character (°). Because of that, I can´t merge this with another Data Frame or rename the column. I don´t get any error message just the name stays the same. What should I do?
This is the code I am using and the result of the Dataframes:
import pandas as pd
import numpy as np
# Importando Planilhas
CRM = pd.ExcelFile(r'C:\Users\Michel\Desktop\Relatorio de
Vendas\relatorio_vendas_CRM.xlsx', encoding= 'utf-8')
protheus = pd.ExcelFile(r'C:\Users\Michel\Desktop\Relatorio de
Vendas\relatorio_vendas_protheus.xlsx', encoding= 'utf-8')
#transformando em Data Frame
df_crm = CRM.parse('190_pedido_export (33)')
df_protheus = protheus.parse('Relatorio de Pedido de Venda')]
# Transformando Campos em float o protheus
def turn_to_float(x):
return np.float(x)
df_protheus["TES"] = df_protheus["TES"].apply(turn_to_float)
df_protheus["Qtde"] = df_protheus["Qtde"].apply(turn_to_float)
df_protheus["Valor"] = df_protheus["Valor"].apply(turn_to_float)
#Tirando Tes de não venda do protheus
# tirando valores com código errado 6
df_protheus_1 = df_protheus[df_protheus.TES != 513.0]
df_protheus_2 = df_protheus_1[df_protheus_1.TES != 576.0]
**df_crm.columns = df_crm.columns.str.replace('N° Pedido', 'teste')
df_crm.columns**
Orçamento Origem N° Pedido Nº Pedido ERP Estabelecimento Tipo de
Pedido Classificação(Tipo) Aplicação Conta CNPJ/CPF Contato ...
Aprovação Parcial Antecipa Entrega Desconto da Tabela de Preço
Desconto do Cliente Desconto Informado Observações Observações NF Vl
Total Bruto Vl Total Completo
0 20619.0 23125 NaN Optitex 1 - Venda NaN Industrialização/Revenda
XAVIER E ARAUJO LTDA ME 7970626000170 NaN ... N N 0 0 0
Note that I used other codes for the bold part with the same result:
#renomeando tabela para dar Merge
#df_crm['proc'] = df_crm['N\xc2\xb0 Pedido']
#df_crm['N Pedido'] = df_crm['N° Pedido']
#df_crm.drop('N° Pedido',inplace=True,axis=1)
#df_crm
#df_crm['N Pedido'] = df_crm['N° Pedido']
#df.drop('N° Pedido',inplace=True,axis=1)
#df_crm
#df_crm_1 = df_crm.rename(columns={"N°Pedido": "teste"})
#df_crm_1
Thanks for posting the link to the Google Sheet. I downloaded it and loaded it via pandas:
df = pd.read_excel(r'~\relatorio_vendas_CRM.xlsx', encoding = 'utf-8')
df.columns = df.columns.str.replace('°', '')
df.columns = df.columns.str.replace('º', '')
Note that the two replace statements are replacing different characters, although they look very similar.
Help from: Why do I get a SyntaxError for a Unicode escape in my file path?
I was able to copy the values into another column. You could try that
df['N Pedido'] = df['N° Pedido']
df.drop('N° Pedido',inplace=True,axis=1)