Skip to content

Commit f21ab87

Browse files
authoredJun 24, 2024
Add files via upload
1 parent e8ac372 commit f21ab87

35 files changed

+685
-0
lines changed
 

‎ASCII_Manipulation.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
print(ord("A"))
2+
# 65
3+
4+
print(chr(65))
5+
# A
6+
7+
print(unichr(65))
8+
# A (em Python 2)
9+
10+
print(hex(65))
11+
# 0x41
12+
13+
print(oct(65))
14+
# 0101

‎FileManipulationExceptions.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
def ler_arquivo(nome_arquivo):
2+
try:
3+
with open(nome_arquivo, "r") as arquivo:
4+
dados = arquivo.read()
5+
except FileNotFoundError:
6+
print("Arquivo não encontrado")
7+
finally:
8+
# Garante que o arquivo seja fechado
9+
arquivo.close() # Não é necessário com o 'with open'

‎LinearRegressionModels.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import pandas as pd
2+
import numpy as np
3+
from sklearn.linear_model import LinearRegression
4+
5+
# Load the spreadsheet data
6+
df = pd.read_excel("my_spreadsheet.xlsx")
7+
8+
# Create a linear regression model
9+
model = LinearRegression()
10+
11+
# Fit the model to the data
12+
model.fit(df["x"], df["y"])
13+
14+
# Make predictions
15+
predictions = model.predict(df["x"])
16+
17+
# Evaluate the model
18+
print(model.score(df["x"], df["y"]))

‎LoopsControl.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
# Laço while com cláusula else
2+
while True:
3+
print("Loop infinito")
4+
else:
5+
print("O loop chegou ao fim")
6+
7+
# Laço for com cláusula else
8+
for i in range(10):
9+
print(i)
10+
else:
11+
print("O laço terminou")

‎ManipulationPDFS.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import PyPDF2
2+
import re
3+
4+
# Abre o arquivo PDF
5+
pdf_file = open("arquivo.pdf", "rb")
6+
7+
# Cria um objeto PDFReader
8+
pdf_reader = PyPDF2.PdfFileReader(pdf_file)
9+
10+
# Obtém a primeira página do PDF
11+
page = pdf_reader.getPage(0)
12+
13+
# Converte a página em texto
14+
text = page.extractText()
15+
16+
# Procura por uma linha que contenha o texto "Total a recolher"
17+
match = re.search(r"Total a recolher: \d+", text)
18+
19+
# Obtém o valor do total a recolher
20+
total_a_recolher = match.group(1)
21+
22+
# Imprime o valor do total a recolher
23+
print(total_a_recolher)
24+
25+
26+
'''
27+
28+
arquivo_pdf = "arquivo.pdf"
29+
30+
localizado na mesma pasta
31+
32+
'''
33+
34+
'''
35+
36+
import os
37+
38+
# Obtém o caminho do arquivo PDF
39+
arquivo_pdf = os.path.join(os.getcwd(), "arquivo.pdf")
40+
41+
localizado em uma outra pasta
42+
43+
'''

‎Recursion.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
def foo(a):
2+
return a + a + a
3+
4+
b = 1
5+
6+
b = foo(b)
7+
8+
b = foo(b)
9+
10+
b = foo(b)

‎Recursion2.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
def foo(a):
2+
return a + a + a
3+
4+
b = 1
5+
6+
foo(b)
7+
8+
foo(b)
9+
10+
foo(b)
11+
12+
print(b)

‎Recursivity.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
def foo(a):
2+
return a + a + a
3+
4+
b = 1
5+
6+
foo(b)
7+
8+
foo(b)
9+
10+
foo(b)
11+
12+
print(b)

‎ValuesComparison.py

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
import pandas as pd
2+
import zipfile
3+
import PyPDF2
4+
import os
5+
6+
# Define the ZIP file path
7+
zip_file_path = "file.zip"
8+
9+
# Extract files from the ZIP file using context manager and extractall
10+
with zipfile.ZipFile(zip_file_path, "r") as zip_file:
11+
zip_file.extractall("DecompressedFiles") # Extract to a directory
12+
13+
14+
# Function to convert PDF to CSV (using a more robust method)
15+
def convert_pdf_to_csv(pdf_file):
16+
with open(pdf_file, "rb") as pdf:
17+
reader = PyPDF2.PdfReader(pdf)
18+
num_pages = len(reader.pages)
19+
data = []
20+
for page_num in range(num_pages):
21+
page = reader.pages[page_num]
22+
text = page.extract_text()
23+
data.extend(text.split("\n"))
24+
return data # Return all extracted lines
25+
26+
# Extract data from PDF files (using the corrected paths)
27+
file_transmission_data = convert_pdf_to_csv("DecompressedFiles/file_transmission.pdf")
28+
taxDate = convert_pdf_to_csv("DecompressedFiles/tax_benefits.pdf")
29+
guideDate = convert_pdf_to_csv("DecompressedFiles/dar.pdf")
30+
31+
# Extract taxMarketShare values (handling potential IndexError)
32+
file_transmission_values = []
33+
taxValues = []
34+
guideValues = []
35+
for line in file_transmission_data:
36+
parts = line.split("|")
37+
if len(parts) > 7:
38+
file_transmission_values.append(parts[7])
39+
for line in taxDate:
40+
parts = line.split("|")
41+
if len(parts) > 5:
42+
taxValues.append(parts[5])
43+
for line in guideDate:
44+
parts = line.split("|")
45+
if len(parts) > 5:
46+
guideValues.append(parts[5])
47+
48+
# Compare taxMarketShare values with error handling (zip) for better performance
49+
for file_trans, tax, guide in zip(file_transmission_values, taxValues, guideValues):
50+
if file_trans != tax or tax != guide: # Check if any pair doesn't match
51+
print(f"Error: DocumentValue of taxMarketShare doesn't match in line '{file_trans}|{tax}|{guide}'")
52+
break
53+
else:
54+
print("All taxMarketShare values match across documents.") # Indicate success if loop completes
55+
56+
57+
58+
# Create a new Excel spreadsheet in .odt format (OpenDocument format)
59+
taxMarketShare_data = {
60+
"Date Limit": [line.split("|")[0] for line in file_transmission_data if len(line.split("|")) > 0], # Error handling for index
61+
"Code Representation": [line.split("|")[1] for line in file_transmission_data if len(line.split("|")) > 1],
62+
"Document Value": file_transmission_values[:len(file_transmission_data)] # Handle length differences
63+
}
64+
65+
taxMarketShare_data_frame = pd.DataFrame(taxMarketShare_data)
66+
taxMarketShare_data_frame.to_excel("SpreadSheet.odt", engine='odf', index=False) # Save as .odt

‎Yield.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
def geradores():
2+
for i in range(10):
3+
yield i
4+
5+
it = geradores()
6+
print(next(it))
7+
print(next(it))
8+
print(next(it))

‎aiStatics.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
from google.cloud import dialogflow_v2
2+
3+
# Create a Dialogflow client
4+
client = dialogflow_v2.AgentsClient()
5+
6+
# Get the agent ID
7+
agent_id = "YOUR_AGENT_ID"
8+
9+
# Get the statistics
10+
statistics = client.get_agent_statistics(agent_id)
11+
12+
# Print the statistics
13+
print(statistics)
14+
15+
16+
# Get the average time spent using the chat
17+
average_time_spent = statistics.conversations_duration_seconds / statistics.conversations_count
18+
19+
# Print the average time spent
20+
print(average_time_spent)
21+
22+
# Get the statistics for each topic
23+
topic_statistics = statistics.topics_statistics
24+
25+
# Print the statistics for each topic
26+
for topic_statistics in topic_statistics:
27+
print(topic_statistics.topic_name, topic_statistics.conversations_count)

‎bankAverageBalance.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
SELECT
2+
AVG(balance) AS average_balance
3+
FROM
4+
bank_accounts

‎constructorMethods.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
class MyClass:
2+
def __new__(cls, *args, **kwargs):
3+
print("Creating a new instance of MyClass")
4+
return super().__new__(cls, *args, **kwargs)
5+
6+
def __init__(self):
7+
print("Initializing the new instance of MyClass")
8+
9+
my_object = MyClass()

‎dataWebsite.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import requests
2+
from bs4 import BeautifulSoup
3+
4+
url = 'URL_DO_SEU_SITE'
5+
response = requests.get(url)
6+
soup = BeautifulSoup(response.content, 'html.parser')
7+
8+
# Extrair tags <script> (JavaScript)
9+
scripts = soup.find_all('script')
10+
for script in scripts:
11+
print(script.text)
12+
13+
# Extrair tags <style> (CSS)
14+
styles = soup.find_all('style')
15+
for style in styles:
16+
print(style.text)

‎decorator.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
class Singleton:
2+
_instance = None
3+
4+
def __new__(cls, *args, **kwargs):
5+
if cls._instance is None:
6+
cls._instance = super().__new__(cls, *args, **kwargs)
7+
return cls._instance
8+
9+
singleton = Singleton()
10+
singleton2 = Singleton()
11+
12+
print(singleton)
13+
print(singleton2)

‎decoratorSet.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
def setter(name):
2+
def inner(func):
3+
def wrapper(self, value):
4+
setattr(self, name, value)
5+
func(self, value)
6+
return wrapper
7+
return inner

‎delObject.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
class MyClass:
2+
def __init__(self, filename):
3+
self.file = open(filename, "w")
4+
5+
def __del__(self):
6+
if self.file is not None:
7+
self.file.close()
8+
9+
my_object = MyClass("my_file.txt")
10+
11+
# The file is now open
12+
13+
del my_object
14+
15+
# The file is now closed

‎filePresence.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import zipfile
2+
3+
# Abre o arquivo zip
4+
with zipfile.ZipFile("arquivo.zip", "r") as zip:
5+
6+
# Lista os arquivos do arquivo zip
7+
for arquivo in zip.namelist():
8+
9+
# Verifica se o arquivo é um dos arquivos necessários
10+
if arquivo == "arquivo1.txt" or arquivo == "arquivo2.txt":
11+
12+
# O arquivo está presente
13+
print("O arquivo {} está presente.".format(arquivo))
14+
15+
else:
16+
17+
# O arquivo não está presente
18+
print("O arquivo {} não está presente.".format(arquivo))

‎manipulatingExcel.py

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
import pandas as pd
2+
3+
# Carregar o arquivo Excel
4+
df = pd.read_excel("meu_arquivo.xlsx")
5+
6+
# Obter a coluna C
7+
coluna_c = df["C"]
8+
9+
Iterar sobre as células preenchidas da coluna C
10+
11+
for valor in coluna_c.dropna():
12+
# Processar o valor da célula
13+
print(valor)
14+
# ...
15+
16+
# Another Manner
17+
18+
import numpy as np
19+
20+
# Carregar o arquivo Excel
21+
data = np.loadtxt("meu_arquivo.xlsx", dtype=str, skiprows=1)
22+
23+
# Obter a coluna C
24+
coluna_c = data[:, 2]
25+
26+
# Iterar sobre as células preenchidas da coluna C
27+
for valor in coluna_c:
28+
if valor != '':
29+
# Processar o valor da célula
30+
print(valor)
31+
# ...
32+
33+
34+
35+
#Now using openpyxl
36+
37+
from openpyxl import load_workbook
38+
39+
# Carregar o arquivo Excel
40+
wb = load_workbook("meu_arquivo.xlsx")
41+
42+
# Acessar a planilha
43+
sheet = wb.active
44+
45+
# Obter a coluna C
46+
coluna_c = sheet['C']
47+
48+
# Iterar sobre as células preenchidas da coluna C
49+
for cell in coluna_c[2:]: # Ignora a primeira linha (cabeçalho)
50+
if cell.value is not None:
51+
# Processar o valor da célula
52+
print(cell.value)
53+
# ...

‎marketList.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
#It's breakfast time, we don't have any fruit at home, we need to go to supermarket, but we need a organized list
2+
3+
#solution
4+
5+
const fruitsArray = ['maçãs', 'bananas', 'laranjas', 'morangos', 'kiwis'];
6+
7+
function fruitsList(fruit) {
8+
return `- ${fruit} (2 unidades)`;
9+
}
10+
11+
#using the .map() method to create a market buy list based on fruits array
12+
13+
const newArrayOfStrings = fruitsArray.map(fruitsList);
14+
15+
console.log('Lista de Compras de Frutas:');
16+
console.log(newArrayOfStrings.join('\n'));
17+
18+
19+
"""
20+
21+
result:
22+
23+
Lista de Compras de Frutas:
24+
- maçãs (2 unidades)
25+
- bananas (2 unidades)
26+
- laranjas (2 unidades)
27+
- morangos (2 unidades)
28+
- kiwis (2 unidades)
29+
30+
"""
31+
32+
33+

‎minimumFlips.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
def minimumFlips(target: str) -> int:
2+
"""
3+
Calculates the minimum number of flips required to transform a binary string to the target state.
4+
5+
Args:
6+
target: The target binary string (e.g., "0011").
7+
8+
Returns:
9+
The minimum number of flips required (int), or None if the input is not a valid string.
10+
"""
11+
12+
if not isinstance(target, str) or not all(char in "01" for char in target):
13+
return None # Check for valid input
14+
15+
flips = 0
16+
current_state = '0'
17+
18+
for char in target:
19+
if char != current_state:
20+
flips += 1
21+
current_state = char
22+
23+
return flips
24+
25+
# Test cases for minimumFlips
26+
assert minimumFlips("0011") == 1
27+
assert minimumFlips("101") == 2
28+
assert minimumFlips("0") == 0
29+
assert minimumFlips("111000") == 2
30+
assert minimumFlips("11011101111") == 3
31+
assert minimumFlips(None) == None
32+
assert minimumFlips("abc") == None
33+
34+
if __name__ == '__main__':
35+
target = input().strip()
36+
result = minimumFlips(target)
37+
print(result)

‎newMethod.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
class Singleton:
2+
_instance = None
3+
4+
def __new__(cls, *args, **kwargs):
5+
if cls._instance is None:
6+
cls._instance = super().__new__(cls, *args, **kwargs)
7+
return cls._instance
8+
9+
singleton = Singleton()
10+
singleton2 = Singleton()
11+
12+
print(singleton)
13+
print(singleton2)

‎pandasCSV.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
# Create a CSV file with some data
2+
data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
3+
with open("my_data.csv", "w") as f:
4+
writer = csv.writer(f)
5+
writer.writerows(data)
6+
7+
# Open the CSV file in Bard
8+
with open("my_data.csv") as f:
9+
df = pd.read_csv(f)
10+
11+
# Insert the data into Bard
12+
df.to_bard()

‎pdfPlumber.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import pdfplumber
2+
3+
# Abrir o arquivo PDF
4+
with pdfplumber.open("arquivo.pdf") as document:
5+
6+
# Obter a primeira página
7+
page = document.get_page(0)
8+
9+
# Obter a caixa de texto
10+
box = page.find_text("Nome do Cliente")
11+
12+
# Extrair o texto da caixa de texto
13+
text = box.extract_text()
14+
15+
# Imprimir o texto
16+
print(text)

‎personalizatedList.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
SELECT
2+
customer_id,
3+
COUNT(product_id) AS number_of_products_viewed
4+
FROM
5+
product_views
6+
WHERE
7+
customer_id = '1234567890'
8+
AND
9+
date_created BETWEEN '2023-01-01' AND '2023-12-31'
10+
GROUP BY
11+
customer_id
12+
ORDER BY
13+
number_of_products_viewed DESC

‎printContacts.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
contacts = [
2+
('James', 42),
3+
('Amy', 24),
4+
('John', 31),
5+
('Amanda', 63),
6+
('Bob', 18)
7+
]
8+
9+
name = input("Digite o nome da pessoa: ")
10+
11+
# Verifica se o nome está na lista
12+
if name in contacts:
13+
# Imprime o nome e a idade
14+
print(f"{name} {contacts[contacts.index(name)][1]}")
15+
else:
16+
# Imprime "Not found"
17+
print("Not found")
18+
19+
'''
20+
21+
Este código irá primeiro obter o nome da pessoa do usuário.
22+
Em seguida, ele usará a expressão in para verificar se o nome está na lista.
23+
Se o nome estiver na lista, o código irá imprimir o nome e a idade da pessoa.
24+
Se o nome não estiver na lista, o código irá imprimir "Not found".
25+
'''

‎printContactsByIndex.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
contacts = [
2+
('James', 42),
3+
('Amy', 24),
4+
('John', 31),
5+
('Amanda', 63),
6+
('Bob', 18)
7+
]
8+
9+
name = input("Digite o nome da pessoa: ")
10+
11+
# Verifica se o nome está na lista
12+
index = contacts.index(name)
13+
14+
if index != -1:
15+
# Imprime o nome e a idade
16+
print(f"{name} {contacts[index][1]}")
17+
else:
18+
# Imprime "Not found"
19+
print("Not found")

‎pythonRandomFunction.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import random
2+
3+
# Create a list of possible street names
4+
possible_street_names = ["Main Street", "Broadway", "Park Avenue", "Wall Street", "Oak Street"]
5+
6+
# Create a list of possible city names
7+
possible_city_names = ["New York", "Los Angeles", "Chicago", "Houston", "Philadelphia"]
8+
9+
# Create a list of possible state names
10+
possible_state_names = ["New York", "California", "Illinois", "Texas", "Pennsylvania"]
11+
12+
# Create a list of possible zip codes
13+
possible_zip_codes = ["10001", "90001", "60601", "77001", "19101"]
14+
15+
# Create a function to generate a random address
16+
def generate_random_address():
17+
return f"{random.choice(possible_street_names)}, {random.choice(possible_city_names)}, {random.choice(possible_state_names)} {random.choice(possible_zip_codes)}"
18+
19+
# Generate a random address
20+
random_address = generate_random_address()
21+
22+
# Print the random address
23+
print(random_address)

‎pythonRandomFunction2.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import random
2+
3+
# Create a list of possible company names
4+
possible_company_names = ["Acme Corporation", "Google", "Microsoft", "Apple", "Amazon"]
5+
6+
# Create a function to generate a random company name
7+
def generate_random_company_name():
8+
return random.choice(possible_company_names)
9+
10+
# Generate a random company name
11+
random_company_name = generate_random_company_name()
12+
13+
# Print the random company name
14+
print(random_company_name)

‎selfMethod.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
class Test:
2+
__egg = 7
3+
4+
def get_egg(self):
5+
return self.__egg
6+
7+
t = Test()
8+
print(t.get_egg())

‎sixOccurrencies.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
def numero_de_ocorrencias(limite):
2+
"""Retorna o número de ocorrências do dígito 6 nos números de 0 a `limite`."""
3+
total = 0
4+
for i in range(1, limite + 1):
5+
total += numero_de_ocorrencias_em_um_numero(i)
6+
return total
7+
8+
def numero_de_ocorrencias_em_um_numero(numero):
9+
"""Retorna o número de ocorrências do dígito 6 em um número."""
10+
if numero < 10:
11+
if numero == 6:
12+
return 1
13+
else:
14+
return 0
15+
else:
16+
dezenas = numero // 10
17+
unidades = numero % 10
18+
if unidades == 6:
19+
return 1
20+
elif dezenas == 6:
21+
return 2
22+
else:
23+
return 0
24+
25+
print(numero_de_ocorrencias(1536))

‎staticMethod.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
class Shape:
2+
@staticmethod
3+
def area(width, height):
4+
return width * height
5+
6+
w = int(input())
7+
h = int(input())
8+
9+
print(Shape.area(w, h))

‎withAnalysysExceptions.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
def withdraw(amount):
2+
try:
3+
account_balance = 1000
4+
if amount > account_balance:
5+
raise ValueError("Insufficient funds")
6+
elif not isinstance(amount, int):
7+
raise TypeError("Amount must be an integer")
8+
print(str(amount) + " withdrawn!")
9+
except ValueError as e:
10+
print(e)
11+
except TypeError as e:
12+
print(e)
13+
14+
# Add a finally block to clean up any resources that were opened in the try block
15+
finally:
16+
# Do something to clean up resources, such as closing a file
17+
pass
18+
19+
# Get the amount to withdraw from the user
20+
amount = int(input("Enter the amount to withdraw: "))
21+
22+
# Withdraw the amount from the user's account
23+
withdraw(amount)

‎withdrawAboveCapacity.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
def sacar_dinheiro(valor):
2+
try:
3+
# Código que pode gerar exceções
4+
if valor > 1000:
5+
raise ValueError("Valor de saque muito alto")
6+
print(f"{valor} sacado com sucesso!")
7+
except ValueError as e:
8+
print(e)

‎zipFilesManipulation.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import zipfile
2+
import os
3+
import pandas as pd
4+
5+
def extract_data_from_files(zip_file_path, file_names, column_names, value_column_name, code_column_name):
6+
# Extract files from the ZIP file using context manager and extractall
7+
with zipfile.ZipFile(zip_file_path, "r") as zip:
8+
zip.extractall("arquivo_descompactado") # Extract to a directory
9+
10+
# Extract values from the extracted files
11+
data_frames = []
12+
for file_name in file_names:
13+
file_path = os.path.join("arquivo_descompactado", file_name) # Construct full file path
14+
with open(file_path, "r") as file: # Use the corrected file path
15+
data_frame = pd.DataFrame()
16+
for line in file:
17+
values = line.split("|")
18+
19+
# Ensure the expected number of values in the line
20+
if len(values) >= max(value_column_name, code_column_name) + 1:
21+
data_frame = data_frame.append({
22+
column_names[0]: values[0],
23+
column_names[1]: values[1],
24+
value_column_name: values[value_column_name],
25+
"Observations": "Correct" # You might want to customize this based on your data
26+
}, ignore_index=True)
27+
data_frames.append(data_frame)
28+
29+
# Merge the extracted data frames
30+
merged_data_frame = pd.concat(data_frames)
31+
32+
# Save the merged data frame to an OpenDocument spreadsheet (.ods)
33+
merged_data_frame.to_excel("planilha.ods", engine='odf', index=False)
34+
35+
# Example usage
36+
zip_file_path = "arquivo.zip"
37+
file_names = ["new_name_1.txt", "new_name_2.txt", "new_name_3.txt"]
38+
column_names = ["Data", "Código"]
39+
value_column_name = 7
40+
code_column_name = 1
41+
42+
extract_data_from_files(zip_file_path, file_names, column_names, value_column_name, code_column_name)

0 commit comments

Comments
 (0)
Please sign in to comment.