jueves, 31 de octubre de 2024

count lens of element on a list, and create a dict if value is greater than

>>> words

['cat', 'window', 'defenestrate']

>>> 


 >>> {a:len(a) for a in words if len(a)>5}

{'window': 6, 'defenestrate': 12}


Flow control and function

 https://docs.python.org/3/tutorial/controlflow.html#if-statements

miércoles, 30 de octubre de 2024

google sheet reading pytthon

  1. Create a Google Cloud Platform (GCP) project

Go to the Google Cloud Console by clicking the link below :

The link will direct you to this page.

Create a new project by clicking ‘Go to create a project button on the above page’ or directly by using the link below. If you already have a project, you can select that one instead.

The link will direct you to this page. Enter a project name and create it.

2. Enable the Google Sheets API

In the Cloud Console, navigate to the “APIs & Services” > “Library” section.

Search for “Google Sheets API” and enable it for your project.

Click on the ‘Enable’ button.

3. Create credentials

After enabling the API, go to the “APIs & Services” > “Credentials” section.

Click on the ‘Create credentials’ button and generate an API key.

Copy the API key for future use.

4. Manage Google Sheet Access Permissions

By default, Google Sheets are private. To make them accessible, you’ll need to share the Google Sheet publicly. Navigate to your Google Sheet and click on the ‘Share’ button.

Ensure you choose ‘Anyone with the link’ and set the access to ‘View.

5. Access Sheet Data

Below is the API endpoint to access sheet data. Please update the sheet ID, sheet name, and API key accordingly. You can find the sheet ID in the URL of your Google Sheet page. Look for the string of characters between ‘/d/’ and ‘/edit’ in the URL, and that is your sheet ID.

https://sheets.googleapis.com/v4/spreadsheets/{SHEET_ID}/values/{SHEET_NAME}!A1:Z?alt=json&key={API_KEY}

Next, open the provided URL in your web browser, and you will receive a response similar to this.

{
'range': 'demo_sheet!A1:Z1000',
'majorDimension': 'ROWS',
'values': [
[
'Email id',
'Password',
'count',
'id'
],
[
'demo@gmail.com',
'demopass',
'60',
'0'
]
]
}

6. Retrieve Sheet Data Using Python

Now, let’s write Python code to access this data.

import requests

def get_google_sheet_data(spreadsheet_id,sheet_name, api_key):
# Construct the URL for the Google Sheets API
url = f'https://sheets.googleapis.com/v4/spreadsheets/{spreadsheet_id}/values/{sheet_name}!A1:Z?alt=json&key={api_key}'

try:
# Make a GET request to retrieve data from the Google Sheets API
response = requests.get(url)
response.raise_for_status() # Raise an exception for HTTP errors

# Parse the JSON response
data = response.json()
return data

except requests.exceptions.RequestException as e:
# Handle any errors that occur during the request
print(f"An error occurred: {e}")
return None


# configurations
spreadsheet_id = ''
api_key = ''
sheet_name = "Sheet1"

sheet_data = get_google_sheet_data(spreadsheet_id,sheet_name, api_key)

if sheet_data:
print(sheet_data)
else:
print("Failed to fetch data from Google Sheets API.")

That’s all for now. Thank you for reading! Please feel free to share your suggestions in the comments below.

 
https://medium.com/@techworldthink/accessing-google-sheet-data-with-python-a-practical-guide-using-the-google-sheets-api-dc57759d387a

viernes, 25 de octubre de 2024

Calculadora class

class calculadora:

    def __init__(self, x, y):

        self.x = x

        self.y = y


    def suma(self):

        return self.x + self.y


    def mult(self):

        return self.x * self.y


    def div(self):

        return self.x / self.y


    def resta(self):

        return self.x - self.y


c1 = calculadora(24, 5)


print(c1.suma())

print(c1.mult())

print(c1.div())

print(c1.resta())


viernes, 11 de octubre de 2024

creating a dict from 2 list


Easy way

>>> d=dict(zip([1, 2, 3], ['sugar', 'spice', 'everything nice']))

>>> d

{1: 'sugar', 2: 'spice', 3: 'everything nice'}




>>> thedict={item[0]:item[1] for item in zip([1, 2, 3], ['sugar', 'spice', 'everything nice'])}




>>> thedict={item[0]:item[1] for item in zip([1, 2, 3], ['sugar', 'spice', 'everything nice'])}
>>> thedict
{1: 'sugar', 2: 'spice', 3: 'everything nice'}


------------------------------



>>> info={}
>>> [info.update({item[0]:item[1]}) for item in zip([1, 2, 3], ['sugar', 'spice', 'everything nice'])]
[None, None, None]
>>> info
{1: 'sugar', 2: 'spice', 3: 'everything nice'}

searching words on a list

 >>> words

['Ambiorix', 'RODRIGUEZ', 'Placencio', 42, 'AMIGo']

>>> [a for a in words if 'pl' in str(a).lower()]

['Placencio']

>>> [a for a in words if 'amb' in str(a).lower()]

['Ambiorix']

>>> [a for a in words if str(a).lower()=='amigo']

['AMIGo']



>>> l
[2.4, 3, 4, 'amigo', 'Rosa', 'Maria']
>>> [a for a in l if str('ro'.lower()) in str(a).lower()]

miércoles, 9 de octubre de 2024

http handling reponse status

 import requests


url = 'https://example.com'

response = requests.get(url)


if response.status_code == 200:

    print("Success!")

elif response.status_code == 404:

    print("Not Found!")

elif response.status_code == 500:

    print("Server Error!")

# Add more status code checks as needed

else:

    print(f"Received unexpected status code: {response.status_code}")

-------------------



 import requests

from bs4 import BeautifulSoup

import csv

import json


url = 'https://example.com/data'  # Replace with actual URL

response = requests.get(url)


if response.status_code == 200:

    content_type = response.headers.get('Content-Type', '')


    if 'text/html' in content_type:

        soup = BeautifulSoup(response.text, 'html.parser')

        print("HTML content:")

        print(soup.prettify())


    elif 'application/json' in content_type:

        data = response.json()

        print("JSON data:")

        print(data)


    elif 'application/xml' in content_type or 'text/xml' in content_type:

        soup = BeautifulSoup(response.content, 'xml')

        print("XML content:")

        print(soup.prettify())


    elif 'text/plain' in content_type:

        text_content = response.text

        print("Plain text content:")

        print(text_content)


    elif 'text/csv' in content_type:

        csv_content = response.text

        print("CSV content:")

        reader = csv.reader(csv_content.splitlines())

        for row in reader:

            print(row)


    else:

        print("Received unsupported content type:", content_type)

else:

    print(f"Failed to retrieve data. Status code: {response.status_code}")


viernes, 4 de octubre de 2024

Disk usage

 import glob

import subprocess

from prettytable import PrettyTable

from math import log  # Import log from the math module


def convert_size(size_bytes):

    """Convert bytes to a human-readable format (KB, MB, GB)."""

    if size_bytes == 0:

        return "0 Bytes"

    size_names = ["Bytes", "KB", "MB", "GB"]

    i = int(log(size_bytes, 1024))

    p = 1024 ** i

    s = round(size_bytes / p, 2)

    return f"{s} {size_names[i]}"


# Function to fetch and sort disk usage, then print a pretty table

def test(path, extension):

    table = PrettyTable(field_names=["File", "Disk Usage"])

    

    # Collect file sizes and names

    usage_info = []

    for file in glob.glob(f'{path}*.{extension}'):

        if file:

            usage = subprocess.getoutput(f'du -b "{file}"')

            size, _ = usage.split()  # Get size, ignore the rest

            usage_info.append((file, int(size)))  # Store as a tuple of (file, size)

    

    # Sort by size (second element of the tuple)

    usage_info.sort(key=lambda x: x[1], reverse=True)


    # Add sorted data to the table with human-readable sizes

    for file, size in usage_info:

        human_readable_size = convert_size(size)

        table.add_row([file, human_readable_size])


    print(table)


# Get user input for directory path and file extension

path = input("Enter the directory path: ")

file_extension = input("Enter the file extension (without dot): ")


# Example usage

test(path, file_extension)


pip install prettytable




 import glob

import subprocess

from prettytable import PrettyTable


# One-liner with pretty printing

test = lambda a, b: (lambda table: [table.add_row([file, subprocess.getoutput(f'du -h "{file}"')]) for file in glob.glob(f'{a}*.{b}') if file] and print(table))(

    PrettyTable(field_names=["File", "Disk Usage"])

)


# Example usage

test('./', 'txt')


getting file size in a list

 


>>> c=glob.glob('*.wav')

>>> c

['tts_1.wav', 'ss-claro.wav', 'en-US-Studio-O.wav', 'no-disp.wav', 'ss-viva.wav']

>>> 



>>> [subprocess.getoutput(f'du -h {a}').split() for a in c]

[['168K', 'tts_1.wav'], ['768K', 'ss-claro.wav'], ['96K', 'en-US-Studio-O.wav'], ['352K', 'no-disp.wav'], ['508K', 'ss-viva.wav']]

>>> 



du -h *.wav

96K en-US-Studio-O.wav

352K no-disp.wav


------------


>>> fs=lambda a:glob.glob(f'*.{a}')

>>> fs('mp3')
['output.mp3', 'tts_1.mp3', '1.mp3']



----------


 fs=lambda path,files:glob.glob(f'{path}*.{files}')


>>> fs('/home/ambiorixg12/Downloads/','txt')
['/home/ambiorixg12/Downloads/index.php.txt', '/home/ambiorixg12/Downloads/MicroSIP_log (1).txt', '/home/ambiorixg12/Downloads/task.txt', '/home/ambiorixg12/Downloads/FC61FA41-E334-5D8C-B80E-C80638B68203.txt', '/home/ambiorixg12/Downloads/50225054-BCCC-57A2-8C29-5318E213BD05.txt']
>>> 

>>> test= lambda a,b: [subprocess.getoutput(f'du -h {a}').split() for a in fs(a,b)]

 test('/home/ambiorixg12/Downloads/','mp3')


------------------------------------------------------------
function  1


>>> fs=lambda a:glob.glob(f'*.{a}')
>>> fs('mp3')
['output.mp3', 'tts_1.mp3', '1.mp3']

function 2
>>> test= lambda a: [subprocess.getoutput(f'du -h {a}').split() for a in fs(a)]

>>> test('mp3')


[['12K', 'output.mp3'], ['32K', 'tts_1.mp3'], ['96K', '1.mp3']]



-------

serching files on the system from a list

  1. import subprocess
  2.  
  3. c=subprocess.getoutput('ls')
  4.  
  5. r=[a for a in c.split() if 'chat' in a.lower()]
  6.  
  7.  
  8. print(r)
  9. c
  10. ['chatbot.py', 'ChatGPT.pdf']
  11.  
  12.  
  13.  
  14.  
  15. looking from a list will search all mp3 and mp4 and pdf file and will return a list with sub list for each category
  16.  
  17.  
  18.  
  19. >>> [[a for a in c.split() if d.lower() in a.lower()] for d in ['mp3','mp4','pdf']]
  20. [['1.mp3', 'output.mp3', 'tts_1.mp3'], ['pp.mp4'], ['ChatGPT.pdf', 'PDF']]