martes, 16 de julio de 2024

converting a nested list ain a singel list

>>> nested_list

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

 

>>> list=[]

>>> for  m in nested_list:

...    for t in m:

...       list.append(t)

... 

>>> list

[1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> 

>>> 


>>> 


lunes, 15 de julio de 2024

Python response module

Exceptions and Warnings

ConnectTimeout:


import requests from requests.exceptions import ConnectTimeout try: response = requests.get('https://httpbin.org/delay/10', timeout=1) except ConnectTimeout: print("The request timed out while trying to connect to the server.")

########################

ConnectionError:

from requests.exceptions import ConnectionError
try: response = requests.get('1http://thisurldoesnotexist.com') except ConnectionError: print("A network problem occurred.")

#################

DependencyWarning:



import warnings from requests import DependencyWarning warnings.warn("This is a DependencyWarning", DependencyWarning)

################

FileModeWarning:


import warnings from requests import FileModeWarning warnings.warn("This is a FileModeWarning", FileModeWarning)

#####################

HTTPError:



from requests.exceptions import HTTPError try: response = requests.get('https://httpbin.org/status/404') response.raise_for_status() except HTTPError as http_err: print(f"HTTP error occurred: {http_err}")

######################################

JSONDecodeError:

from requests.exceptions import JSONDecodeError
try: response = requests.get('https://httpbin.org/get') data = response.json() except JSONDecodeError: print("Failed to decode JSON response.")

#####

NullHandler:

import logging from requests import NullHandler logger = logging.getLogger('example_logger') logger.addHandler(NullHandler()) logger.info('This will not be output anywhere')


############

ReadTimeout:

from requests.exceptions import ReadTimeout try: response = requests.get('https://httpbin.org/delay/3', timeout=1) except ReadTimeout: print("The server did not send any data in the allotted amount of time.")



sábado, 13 de julio de 2024

viernes, 12 de julio de 2024

Running Linux command and saving as string

 You can run a Linux command in Python and save the output as a Python variable using the subprocess module. Here’s how you can do it:

  1. Import the subprocess module.
  2. Use the subprocess.run() function to execute the command.
  3. Capture the output by setting the stdout parameter to subprocess.PIPE.
  4. Decode the output from bytes to a string if needed.

Here’s an example:

python
import subprocess # Run the command and capture the output result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE, text=True) # Save the output as a Python variable output = result.stdout # Print the output print(output)

In this example, the ls -l command is executed, and its output is captured and stored in the output variable. The text=True parameter is used to ensure that the output is returned as a string instead of bytes.

Detailed Explanation:

  • subprocess.run(['ls', '-l'], stdout=subprocess.PIPE, text=True):
    • The command ls -l is passed as a list of arguments.
    • stdout=subprocess.PIPE captures the standard output of the command.
    • text=True ensures that the output is returned as a string.
  • result.stdout contains the output of the command.

Another Example:

Here’s another example where we run the uname -a command to get system information:

python
import subprocess # Run the command and capture the output result = subprocess.run(['uname', '-a'], stdout=subprocess.PIPE, text=True) # Save the output as a Python variable output = result.stdout # Print the output print(output)

In this example, the uname -a command is executed, and its output is stored in the output variable.

Error Handling:

You can also add error handling to capture any errors that might occur during the execution of the command:

python
import subprocess try: # Run the command and capture the output result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=True) # Save the output as a Python variable output = result.stdout # Print the output print(output) except subprocess.CalledProcessError as e: print(f"Error: {e.stderr}")

In this example, any errors during the execution of the command will be caught, and the error message will be printed. The check=True parameter ensures that an exception is raised if the command exits with a non-zero status.

Couting occurance of a character

from math import pi

print(pi)

list=[]

dict={}

for a in str(pi):

    list.append(a)


b=set(sorted(list))

print(b)

for c in b:

    dict.update({c:list.count(c)})

print(dict)

Python String slicing

 >>> s="Ambiorix"



s[2]  #print  index  3 'b' remember index start from  0



s[2:]  #remove first 2 line  and print everyhing    'biorix'



 s[:2] #  print first 2 chars  'Am'


 s[:-2]  #'Ambior' remove last 2 chars



s[-2:]    # print the last 2  chargs  'ix'



 s[-2]     # print the char before the last value  'i'

Get index

>>> for a,b in enumerate(s):

...    print(a,b)

... 

0 A

1 m

2 b

3 i

4 o

5 r

6 i

7 x


cuando se utiliza la notación de slicing en una cadena (o lista), la sintaxis es:

python

s[start_index : before_end_index]

Donde:

  • start_index es el índice inicial desde donde se comenzará a extraer la subcadena (o sublista).
  • before_end_index es el índice hasta el cual se extraerá la subcadena (o sublista), pero sin incluir el carácter (o elemento) en esta posición.

Por ejemplo, para la cadena s = 'Ambiorix':


s[2:4]

Esto significa que se comenzará a extraer desde el índice 2 y se detendrá justo antes del índice 4. Por lo tanto, los caracteres en los índices 2 y 3 serán seleccionados.

Así, s[2:4] resulta en 'bi', que son los caracteres en los índices 2 y 3 de la cadena s.

Aquí hay un ejemplo generalizado:

ps = 'Ambiorix'
print(s[2:5]) # Esto resultará en 'bio' print(s[:3]) # Esto resultará en 'Amb', empezando desde el inicio hasta antes del índice 3 print(s[4:]) # Esto resultará en 'orix', desde el índice 4 hasta el final print(s[:]) # Esto resultará en 'Ambiorix', que es la cadena completa

Cada una de estas operaciones de slicing sigue la misma regla: s[start_index : before_end_index].

viernes, 21 de junio de 2024

Reg cookbook

Here's how you can correctly match the first word in a string:

  1. import re
  2.  
  3. text = "subject, adjust, jump, university, major"
  4.  
  5. # Match the first word in the string
  6. match = re.match(r"^\w+", text, flags=re.IGNORECASE)
  7.  
  8. if match:
  9. print(match.group())
  10. else:
  11. print("No match found")



To match the last word 

in a string, you can use regular expressions combined with string manipulation techniques. The approach varies slightly depending on whether you use re.findall, re.search, or another method.

Using re.findall

To find the last word using re.findall, you would typically capture all words and then select the last one:

  1. import re
  2.  
  3. text = "subject, adjust, jump, university, major"
  4.  
  5. # Find all words in the string
  6. words = re.findall(r'\w+', text, flags=re.IGNORECASE)
  7.  
  8. # Get the last word
  9. last_word = words[-1] if words else None
  10.  
  11. print(last_word)
  12.  

 Match Words Starting with "gob"


  1. import re
  2.  
  3. text = "goblin, goblet, gobsmacked, gobble, dog, gob"
  4.  
  5. # Find words starting with 'gob'
  6. matches = re.findall(r'\bgob\w*', text, flags=re.IGNORECASE)
  7.  
  8. print(matches)

Explanation

  • \bgob\w*:
    • \b asserts a word boundary before "gob".
    • gob is the specific prefix we are looking for.
    • \w* matches zero or more word characters following "gob".


3. Match Words Ending with "te"

  1. import re
  2.  
  3. text = "complete, update, bite, great, late, state"
  4.  
  5. # Find words ending with 'te'
  6. matches = re.findall(r'\b\w*te\b', text.lower())
  7.  
  8. print(matches)
  9.  

    Explanation

    • \b\w*te\b:
      • \b asserts a word boundary.
      • \w* matches zero or more word characters preceding "te".
      • te is the suffix we are looking for.
      • \b asserts a word boundary to ensure "te" is at the end of the word.



The matches list will contain all words from the text that have the substring "uj" in them. For the provided text, the output will be:

  1. import re
  2.  
  3. text = "subject, adjust, jump, university, major" # Find words containing 'uj' (case-insensitive)
  4.  
  5. matches = re.findall(r'\b\w*uj\w*\b', text, flags=re.IGNORECASE)
  6.  
  7. print(matches)
  8.  
Explanation
  • r'\b\w*uj\w*\b':

    • \b is a word boundary anchor, which ensures that the match occurs at the beginning or end of a word. It's useful if you want to match whole words but is optional if you're just looking for substrings within words.
    • \w* matches any number of word characters (letters, digits, and underscores) before and after the substring uj.
    • uj is the substring you're looking to match within the words.
  • Flags: re.IGNORECASE makes the search case-insensitive.



Match emails
matches = re.findall(r'\b[\w.-]+@[a-zA-Z-]+\.[a-zA-Z.]{2,6}\b', text)

return  string after @
import re 
 text = "Email me at john.doe@example.com or jane_smith123@test.co.uk"
matches = re.findall(r'@(\w+)', text) print(matches)

return before

matches = re.findall(r'(\w+)@', text) 





////////////// todo lo que empiece con a  y seguido de uno o mas caracteres y termine  en r
import re
pattern = r"^a.+r$"   
text1 = "ar"
text2 = "abr"

print(re.findall(pattern, text1))  # No Match
print(re.findall(pattern, text2))  # Match

#^a   // todo lo que empiece con a

#.+   Uno o mas caracteres si quito el signo de mas  solo  podria tener un solo caracter para machar

#r$  // todo lo que termine con r

#final machea todo lo que empiece con a seguido de uno mas caractereres y termine en r   ejemplo machea  abr pero no machea ar


Search  XXX-XXX-XXX phone format

import re
text="ambiorix rodriguez 809-714-2819 809-560-8344 829-561-3454 edad 42"
match=re.findall(r'\d{3}-+\d{3}-\d{4}',text)
print(match)

['809-714-3489', '809-560-8344', '829-561-3454']