Unpack an object from a list - python-docx

i'm triying to parse a bunch of .docx files, using the docx module in python, with this code.
folder = selec_folder()
new_location = os.chdir(folder)
#p =os.getcwd()
#p = os.path.dirname(os.path.abspath(_file_))
#Una lista que guarda los nombres de los archivos con extension .docx
docs = [a for a in os.listdir(new_location) if a.endswith('.docx') and str(a[0]) !='~' ]
#patron regex para buscar lo indicado por el usurio, indicando que se igneren las mayusculas o minusculas
busqueda = re.compile(f'{objetivo}',re.I)
n2 = Document()
#loops para seleccionar cada archivo y luego cada parrafo, para verificar que se encuentre el contenido buscado
for para in docs:
print(f'Nombre del documento------------------>{para}')
doc = Document(para)
print(len(doc.paragraphs))
for i in range(len(doc.paragraphs)):
#print(len(doc.paragraphs[i].runs))
if busqueda.findall(doc.paragraphs[i].text):
p = doc.paragraphs[i].runs
print('this is the len of run -----: ',p)
for i in range(len(p)):
print(p.runs[i])
if p.runs[i].bold == True:
n2.add_run(p.runs[i].text).bold= True
elif doc.paragraphs.runs[i].italic == True:
n2.add_run(p.runs[i].text).italic= True
elif doc.paragraphs.runs[i].underline == True:
n2.add_run(p.runs[i].text).underline = True
## elif doc.paragraphs.runs[i].Font.math == True:
## n2.add_run(doc.paragraphs..runs[i].text).Font.math = True
##
else:
n2.add_run(" ")
#for run in doc.paragraphs[i]:
#salva el documento de word
nuevo_doc.save('Nuevo_documento.docx')
broot = tk.Tk()
broot.destroy()
mensaje = messagebox.showinfo('Proceso concluido','El documento ha sido generado satisfactoriamente')
os.system('start Nuevo_documento.docx')
basically, the programs asks the user to input a subject to look in the files, then ask the user to select a folder (or path) to work with, then it opens every .docx file in the folder, and looks every paragraph, until if finds what is looking for, if found, it copies the whole paragraph with the format (bold, italic, underline, etc), but after adding the if block that checks the runs im getting this error:
Traceback (most recent call last):
File "C:\Users\virlu\Desktop\vdfd\buscaTema1.0.py.py", line 98, in <module>
print(p.runs[i])
i understand that im stracting the objects from a comprehension list, but i can't seem to find a solucition for this, if anyone can held, thanks in advance.
AttributeError: 'list' object has no attribute 'runs'

Related

PySimpleGui how to select the popup_get_text() automatically?

I'm using PySimpleGui for some time and i'm making a Gui with a Database to register products with a wireless barcode scanner, but since i will always be distante from the computer, i wanted to the popup automatically select it's input field, so i can scan another code without needing to click on it, if someone can help me with this and give some hint's to write a better code i will be very grateful.
Tried Searching PySimpleGui documentation,
Tried using pyautogui and other keyboard/mouse modules to press tab or click on it.
i'm expecting to the input field be selected, so i can continue with the scans without needing to click on it every time.
#Libs necessárias
import PySimpleGUI as sg
import Backend
Setores = Backend.Setores()
Produtos = Backend.Produtos()
sg.change_look_and_feel("DarkGrey10")
layout = [
[sg.Text(
"Setor Selecionado: ",
justification='center',
key='-Selecionado-',
size=(42,1),
font=['Arial', '14', 'bold'],
relief='groove'
)],
[sg.Table(
headings=["Setores"],
values=Setores.Lista_De_Setores(),
justification='left',
def_col_width=30,
auto_size_columns=False,
key='-Tabela-',
hide_vertical_scroll=True,
right_click_menu=['Teste', ['Setores', ["Adicionar Setor", "Deletar Setor"], "Adicionar Produto"]])],
[sg.Text("Procurar Setor:"), sg.Input(size=(25,5), key='-Procurar-')],
]
window = sg.Window("Auto Prices", layout, font=["Arial", "18", "bold"], element_justification='center', finalize=True, return_keyboard_events=True, use_custom_titlebar=True)
window['-Tabela-'].bind('<Double-Button-1>', 'Selecionou')
if __name__ == "__main__":
while True:
eventos, valores = window.read()
if eventos == sg.WIN_CLOSED:
break
#===== Testes =====#
if eventos == "Adicionar Produto":
Produtos.Adicionar_Produto()
#========== Adicionar/Deletar Setor ==========#
if eventos == "Adicionar Setor": #Cria um novo Setor
Setores.Adicionar_Setor()
window['-Tabela-'].update(values=Setores.Lista_De_Setores()) # Atualiza a lista de Setores
if eventos == "Deletar Setor":
try: Setores.Deletar_Setor(valores['-Tabela-'][0]) # Deleta o setor que foi selecionado
except: sg.popup_quick_message("Nenhum setor selecionado", background_color='red', font=['arial', '10', 'bold']) #Surge uma janela
window['-Tabela-'].update(values=Setores.Lista_De_Setores()) # Atualiza a lista de Setores
#========== Procurar Setor ==========#
if valores['-Procurar-'] != "":
window['-Tabela-'].update(values=Setores.Procurar_Setor(valores['-Procurar-']))
else:
window['-Tabela-'].update(values=Setores.Lista_De_Setores())
#========== Atualização da interface ==========#
try: #Recebe o nome do setor selecionado
selecionado = Setores.Lista_De_Setores()[valores['-Tabela-'][0]][0]
window['-Selecionado-'].update(f'Setor Selecionado: {selecionado}')
except: pass
Second Script:
import sqlite3
import PySimpleGUI as sg
import pyautogui as pag
from time import sleep
from string import punctuation
from unidecode import unidecode
#Criando Conexão com o DataBase
conexao = sqlite3.connect("Setores.db")
cursor = conexao.cursor()
#========== Funções Produtos =========#
class Produtos:
def Adicionar_Produto(self):
sg.change_look_and_feel("DarkGrey9")
while True:
codigo = sg.popup_get_text(message="Digite o código do produto: ", title="Adicionar Produto", no_titlebar=True, grab_anywhere=True, font=['Arial', '16', 'bold'])
if codigo == None or codigo == '':
break
else:
print(codigo)
#========== Funções Setores =========#
class Setores:
def Adicionar_Setor(self):
sg.change_look_and_feel("DarkGrey9")
data = []
Nome_Setor: str = sg.popup_get_text("Digite o nome do Setor: ", no_titlebar=True, grab_anywhere=True, font=['Arial', '16', 'bold'])
#===== Verifica se o nome do setor tem mais de 3 Letras =====#
if Nome_Setor is not None and len(Nome_Setor) > 3:
Nome_Setor = Nome_Setor.strip(punctuation) # Remove todos os caracteres especiais do nome
Nome_Setor = Nome_Setor.split() # Remove todos os espaços
for _ in Nome_Setor: # Para palavra no nome coloque a primeira letra como maiuscula e o resto minuscula
data.append(_.capitalize())
Nome_Setor = ' '.join(data) # Separa as palavras com um espaço
try: # Se o nome do setor continua sendo maior que 3 caracteres, cria o setor com o nome inserido
if len(Nome_Setor) > 3:
cursor.execute(f"CREATE TABLE '{Nome_Setor}' (Codigo text)")
else:
sg.PopupQuickMessage(f"O Nome {Nome_Setor} é Inválido")
except sqlite3.Error as erro: #Caso ocorra algum erro crie um arquivo ErrorLog com a descrição do erro
if str(erro) == f"table '{Nome_Setor}' already exists":
sg.popup_quick_message("Setor Já Existe", background_color='red', font=['Arial', '18','bold'])
else:
with open("ErrorLog.txt", "a") as arquivo:
arquivo.write(str(erro)+'\n')
def Deletar_Setor(self, Setor):
Setor = self.Lista_De_Setores()[Setor]
print(Setor[0])
try:cursor.execute(f"DROP TABLE '{Setor[0]}'")
except sqlite3.Error as Erro: print(Erro)
def Lista_De_Setores(self):
tables = cursor.execute("SELECT name FROM sqlite_schema WHERE type='table'").fetchall()
Setores = []
for _ in tables:
Setores.append([_[0]])
return Setores
def Procurar_Setor(self, Procurando: str):
tables = cursor.execute("SELECT name FROM sqlite_schema WHERE type='table'").fetchall()
data = []
for _ in tables:
if Procurando in unidecode(str(_[0]).lower()):
data.append([_[0]])
return data

How to write single CSV file using pyspark in Databricks

Good morning all!!
Yesterday I was looking for a function that was able to write a single file CSV with pyspark in Azure Databricks but I did not find anything. So I've built my own function and I wanted to share my solution with the community and if it's possible create like a thread with different solutions for the same problem.
Sorry, because I commented the code in Spanish but basically the function does:
Save the dataframe you've created into a new directory (which is allocated inside the path you've defined and begin with 'temp_') and save the partition there using "coalesce(1)"
Rename the CSV file as you want and moves it to the desired path
Delete de temporary file
That's all! You have your unique CSV file
def escribe_fichero_unico(dataframe, path, file_name, file_format = 'csv'):
"""
Definición: (1) Genera carpeta temporal para guardar particiones que Spark genera por defecto
a la hora de guardar archivos, (2) Une todas las particiones en un único archivo, (3) Mueve este
archivo al directorio anterior y (4) Borra la carpeta temporal
Parámetros:
dataframe: dataframe que quieras guardar como fichero único
file_name: en formato string escribe nombre del archivo
file_format: en formato string escribe 'csv' o 'parquet'
path: en formato string escribe el path donde quieres guardar el csv
"""
import os
# 1) Guardamos el dataframe creando una carpeta temporal que guarda todas las particiones
path_temp = path + 'temp_' + file_name + '_trash'
if file_format == 'csv':
dataframe.coalesce(1).write.format('csv').mode('overwrite') \
.options(header="true", schema="true", delimiter=";") \
.save(path_temp)
else if file_format == 'parquet':
dataframe.coalesce(1).write.format("parquet").mode("overwrite") \
.save(path_temp)
# 2)Une todas las particiones en un único archivo
file_part = [file.path for file in dbutils.fs.ls(path_temp) if os.path.basename(file.path).startswith('part')][0]
# 3) Mueve este archivo al directorio anterior
dbutils.fs.mv(file_part, path + file_name + '.' + file_format)
# 4) Borra la carpeta temporal
dbutils.fs.rm(path_temp, True)
I hope this work for you as well :)

How to fill variables with the content of a Json

I'm starting to work with PowerShell and my first task is to fix a problem with a script that already runs in the production environment.
This script is called via Webhook and it receives a parameter that the webhook passes to it.
I need to run this script inside PowerShell ISE to be able to debug it but I don't know how to fill the variables that are normally filled when it is called by Webhook.
Here is the beginning of the code where the variables are filled in, can someone give me a tip on how to fill the variable "WebHookData"..?
Thanks in advance.
I've tried to do this but it didn't work...
Sorry for putting images instead of the code, but for some reason I can't post the code.
This is the JSON that I use..
{"source":"la-draft-clipboard","value":[{"tokenKey":"8EAD3F03-E08F-4D58-8B1A-2AB8BD2F25DB","type":"literal","tokenExpression":"{"},{"tokenKey":"A7596123-17DF-49A9-AC18-1196A4CD457E","type":"new_line","tokenExpression":"\n"},{"tokenKey":"36DF511D-C1A9-4BC8-B2E9-37BCA058FB78","type":"literal","tokenExpression":" \"AutomationAccountName\": \"proj-00016-automation-account\","},{"tokenKey":"918137AE-EC61-4B77-A5F2-B527E2D4E3C9","type":"new_line","tokenExpression":"\n"},{"tokenKey":"DCC2D1C1-14F0-4869-A44C-08F8AB35B0B3","type":"literal","tokenExpression":" \"BeginPeakTime\": \"7:00\","},{"tokenKey":"61F7441B-0688-4AD2-A1A5-086C4F7F6D1E","type":"new_line","tokenExpression":"\n"},{"tokenKey":"2F3DD3CA-BD83-46EF-9529-C890C2E31CAF","type":"literal","tokenExpression":" \"ConnectionAssetName\": \"AzureRunAsConnection\","},{"tokenKey":"C6DD6FD0-E99A-48A8-96AA-3974D66FD9BD","type":"new_line","tokenExpression":"\n"},{"tokenKey":"A4E7A469-D08A-4C5A-8C6B-06E58996A0EC","type":"literal","tokenExpression":" \"EndPeakTime\": \"17:00\","},{"tokenKey":"E67547BC-98BB-4749-A84E-A36B761EE504","type":"new_line","tokenExpression":"\n"},{"tokenKey":"727D64BD-906C-4DA3-84C5-44F3054B2DEB","type":"literal","tokenExpression":" \"HostPoolName\": \"VDI-POOL-001\","},{"tokenKey":"92AFEBB8-4307-42C2-8BD0-C55ACC848940","type":"new_line","tokenExpression":"\n"},{"tokenKey":"F37993F9-1471-4E58-B43F-9BB08C4D4A03","type":"literal","tokenExpression":" \"LimitSecondsToForceLogOffUser\": 0,"},{"tokenKey":"8B2517D1-046E-43EF-BF75-B1EC5F31B83D","type":"new_line","tokenExpression":"\n"},{"tokenKey":"7464316E-6A8D-4F82-B269-95FF76A69014","type":"literal","tokenExpression":" \"LogOffMessageBody\": \"Salve seus trabalhos! Em aproximadamente 15 minutos, este terminal virtual será desligado automaticamente devido às políticas de otimização de custos da companhia. Caso seja necessário continuar suas atividades, um novo terminal poderá ser acessado após este período.\","},{"tokenKey":"7328955E-0025-4AA1-A0AE-CDAFA4238927","type":"new_line","tokenExpression":"\n"},{"tokenKey":"384AF3CF-CA86-4820-A5E1-230C09909662","type":"literal","tokenExpression":" \"LogOffMessageTitle\": \"ATENÇÃO!!!\","},{"tokenKey":"5E2EBD78-8599-487F-8DC5-CF9699595DDD","type":"new_line","tokenExpression":"\n"},{"tokenKey":"B7E409AF-A5AE-4622-A45E-5982FD15B03E","type":"literal","tokenExpression":" \"MaintenanceTagName\": \"NO_TAG\","},{"tokenKey":"3F9BF963-790D-45B1-9F04-D71A2B7C84DC","type":"new_line","tokenExpression":"\n"},{"tokenKey":"B6E94E37-69C0-4BF8-AE69-CD7B4EA9CB83","type":"literal","tokenExpression":" \"MinimumNumberOfRDSH\": 20,"},{"tokenKey":"00A1D37B-F82B-42F6-B792-75B39EBD6A83","type":"new_line","tokenExpression":"\n"},{"tokenKey":"F41B0C75-4541-4772-BF30-2D4F6DF045C6","type":"literal","tokenExpression":" \"ResourceGroupName\": \"proj-00016-wvd-rg\","},{"tokenKey":"FE6FC329-DC12-4782-83CE-F48BDC6B74B5","type":"new_line","tokenExpression":"\n"},{"tokenKey":"785500F8-3D71-4D91-AADA-D6ABF1EFD66B","type":"literal","tokenExpression":" \"ResourceGroupNameAutomation\": \"proj-00016-automation-rg\","},{"tokenKey":"BD3331BF-3BF9-4B9E-B9B8-C03E448B2D85","type":"new_line","tokenExpression":"\n"},{"tokenKey":"25586050-62A0-4CAF-81FD-C5770DF20B63","type":"literal","tokenExpression":" \"RunbookLogoffShutdown\": \"ARMLogoffAndShutdown\","},{"tokenKey":"C4B9E432-C41D-4374-9531-F2AEFDD51267","type":"new_line","tokenExpression":"\n"},{"tokenKey":"0155B6AB-7CAB-4C4E-BB1F-A643D9B0575B","type":"literal","tokenExpression":" \"SessionThresholdPerCPU\": 0.75,"},{"tokenKey":"3EAA1C7E-0119-40B9-9AF8-85D10E0FA3FD","type":"new_line","tokenExpression":"\n"},{"tokenKey":"2D904698-1386-47D7-9513-7CEE702BA0D3","type":"literal","tokenExpression":" \"TimeDifference\": \"-3:00\""},{"tokenKey":"40D497B6-AAED-4334-81C7-10B8C6745DE0","type":"new_line","tokenExpression":"\n"},{"tokenKey":"18EB90AF-25D4-4956-8A85-41BA555C6A95","type":"literal","tokenExpression":"}"}]}
Based on the JSON you've posted and the parts of the code we can see in the screenshot, give the following mock object a try:
$mockWebhookPayload = [pscustomobject]#{
WebhookName = 'NameOfWebhookGoesHere'
RequestHeader = #{ 'Content-Type' = 'application/json' }
RequestBody = #'
{
"AutomationAccountName": "proj-00016-automation-account",
"BeginPeakTime": "7:00",
"ConnectionAssetName": "AzureRunAsConnection",
"EndPeakTime": "17:00",
"HostPoolName": "VDI-POOL-001",
"LimitSecondsToForceLogOffUser": 0,
"LogOffMessageBody": "Salve seus trabalhos! Em aproximadamente 15 minutos, este terminal virtual será desligado automaticamente devido às políticas de otimização de custos da companhia. Caso seja necessário continuar suas atividades, um novo terminal poderá ser acessado após este período.",
"LogOffMessageTitle": "ATENÇÃO!!!",
"MaintenanceTagName": "NO_TAG",
"MinimumNumberOfRDSH": 20,
"ResourceGroupName": "proj-00016-wvd-rg",
"ResourceGroupNameAutomation": "proj-00016-automation-rg",
"RunbookLogoffShutdown": "ARMLogoffAndShutdown",
"SessionThresholdPerCPU": 0.75,
"TimeDifference": "-3:00"
}
'#
}
& .\path\to\webhook-script.ps1 -WebHookData $mockWebhookPayload

Loading data with JSON.parse: Unexpected token /

I'm pretty new with this JSON and AJAX staff, so I was following a tutorial on youtube: https://www.youtube.com/watch?v=rJesac0_Ftw&t=1029s.
The thing is that I have followed the steps exactly like in the video, but I get the following error:
VM34:1 Uncaught SyntaxError: Unexpected token / in JSON at position 0
at JSON.parse (<anonymous>)
at XMLHttpRequest.theRequest.onload (loader.js:5)
My JSON script:
[
{
"name":"一",
"sound": {
"kunyomi": ["ひと.つ"],
"onyomi": ["イチ"]
},
"description":"Representaba la unidad, el absoluto. Cuando funciona como componente, este carácter adquiere el significado de suelo o de techo según su posición: si se encuentra encima de otro componente, toma el significado de techo; si está debajo, de suelo. Todas las formas antiguas de los números están asociadas a fuerzas del universo y a la mitología. Los números pares son el ying y los impares son el yang.",
"examples":["-月[いちがつ] - Enero", "-日[ついたち] - Día uno", "-回[いっかい] - Dos veces", "-階[いっかい] - Primer Piso"]
},
{
"name":"ニ",
"sound": {
"kunyomi": ["ふた.つ"],
"onyomi": ["ニ、ジ"]
},
"description":"Representa el cielo 一 y la tierra 一, el ying y el yang. Al igual que en el caso de los numerales romanos, el kanji de dos es una simple duplicación del trazo horizontal que significa uno.",
"examples":["二月[にがつ] - Febrero", "二日[ふつか] - Día dos", "二回[にかい] - Dos veces"]
}
]
And I call that JSON with the following code:
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'http://127.0.0.1/japones_flat/kanjis_n5.json');
ourRequest.onload = function() {
"use strict";
var response = JSON.parse(ourRequest.responseText);
console.log(response[0]);
};
ourRequest.send();
I made a little research and it looks like the problem resides in the JSON.parse method, saying that the token "/" is making troubles. After that, I noticed that Dreamweaver had left by default a comment in my .json file, so I deleted it (Because it started with "/") but I keep getting this anoying error. Can you guys help me?
Thanks in advance!

responseAsSlurper error groovy

im having problems trying to encapsulate this sentence in to a groovy function.
-----------------------------------mi call-------------------------------
sizeOfferPrices =
responseAsSlurper.Body.FlightPriceRS.PricedFlightOffers.PricedFlightOffer.OfferPrice.size();
offerAmount = getTotalPrice(sizeOfferPrices)
-----------------------------my function--------------------------------
def getTotalPrice (sizeOfferPrices){
def strTravelersAssociated
def floatImporteViaje = 0
String [] arrTravelersAssociated
def offerAmountTemp
//recorremos los precios que se nos ha devuelto en la oferta
for(i=0; i<=sizeOfferPrices-1; i++){
//obtenemos el precio
offerAmountTemp = responseAsSlurper.Body.FlightPriceRS.PricedFlightOffers.PricedFlightOffer.OfferPrice[i].RequestedDate.PriceDetail.TotalAmount.SimpleCurrencyPrice
offerAmountTemp = offerAmountTemp.toFloat();
//obtenemos los datos de los viajeros asociados , casteamos a string y splitamos para obtener array
strTravelersAssociated = responseAsSlurper.Body.FlightPriceRS.PricedFlightOffers.PricedFlightOffer.OfferPrice[i].RequestedDate.Associations.AssociatedTraveler.TravelerReferences
strTravelersAssociated = strTravelersAssociated.toString();
arrTravelersAssociated = strTravelersAssociated.tokenize(" ");
//obtenemos el numero de viajeros por oferta
intTravelersByOffer = arrTravelersAssociated.size().toInteger();
//realizamos la multiplicaciónd viajeros por su oferta asociada
floatImporteViajeTemp = (offerAmountTemp * intTravelersByOffer).round(2);
floatImporteViaje = floatImporteViaje + floatImporteViajeTemp;
}
//obtenemos el precio total
amount = floatImporteViaje.round(2);
return amount
}
_________________________ERROR_________________________________________
groovy.lang.MissingPropertyException: no such Property
resposeAsSpluger
any suggestions? thanks a lot.
The error is unrelated to the function you've posted, because it's occurring before the function is called. Here's the code where you attempt to call the function
sizeOfferPrices = responseAsSlurper.Body.FlightPriceRS.PricedFlightOffers.PricedFlightOffer.OfferPrice.size();
offerAmount = getTotalPrice(sizeOfferPrices)
The error occurs on the first line (before getTotalPrice is called) because you try to access a property responseAsSlurper which does not exist.