Skip to content

Instantly share code, notes, and snippets.

@raeq
raeq / strings_14_tokenize.py
Created July 19, 2020 13:21
Tokenize a string using NLTK.
import nltk
def tokenize_text(input_str: str = "") -> list:
return nltk.wordpunct_tokenize(input_str)
assert tokenize_text("Good muffins cost $3.88\nin New York.") == [
"Good",
"muffins",
@raeq
raeq / strings_14_base64.py
Created July 19, 2020 13:03
Encode and Decode base64 strings
import base64
def encode_b64(input_string: str = "") -> object:
return base64.b64encode(input_string.encode("utf-8"))
def decode_b64(input_string: str = "") -> object:
return base64.b64decode(input_string).decode("utf-8")
@raeq
raeq / strings_13_url.py
Created July 19, 2020 12:50
Encode and decode UTF-8 URL
import urllib.parse
def encode_url(url: str = "") -> str:
return urllib.parse.quote(url)
def decode_url(url: str = "") -> str:
return urllib.parse.unquote(url)
@raeq
raeq / strings_12_punctuation.py
Created July 19, 2020 12:39
Remove punctuation from a string
import string
def remove_punctuation(input_string: str = "") -> str:
return input_string.translate(str.maketrans("", "", string.punctuation))
assert remove_punctuation("Hello!") == "Hello"
assert remove_punctuation("He. Saw! Me?") == "He Saw Me"
@raeq
raeq / strings_10_execute.py
Created July 19, 2020 12:30
Execute code found in strings
import subprocess
import ast
def exec_string(input_string: str = "") -> str:
result = subprocess.getoutput(input_string)
return result
def eval_string(input_string: str = "") -> str:
@raeq
raeq / strings_6_strip.py
Created July 19, 2020 09:08
Returns a tuple of string stripped
def strip_it(input_string: str) -> tuple:
return (input_string.lstrip(), input_string.rstrip(), input_string.strip())
left, right, full = strip_it(" A padded string ")
assert left == "A padded string "
assert right == " A padded string"
assert full == "A padded string"
@raeq
raeq / strings_5_empty_or_blank.py
Created July 19, 2020 09:01
Is Python String Empty or Blank
def is_null_or_blank(input_string: str = "") -> bool:
if input_string:
if input_string.strip():
return False
return True
assert is_null_or_blank(None) == True
assert is_null_or_blank("") == True
@raeq
raeq / strings_8_file_to_list.py
Created July 19, 2020 08:49
Return a list from a file path
def file_to_list(filename: str = "") -> list:
with open(filename, "r") as f:
lines = list(f)
return lines
assert len(file_to_list("<PATH TO FILE>")) == LINE_COUNT
@raeq
raeq / strings_17s_csv.py
Created July 18, 2020 22:25
List to csv
def from_list(line: list = []) -> str:
ret = ", ".join(e for e in line)
return ret
assert from_list(["a", "b", "c"]) == "a, b, c"
assert from_list(["one", "two", "three"]) == "one, two, three"
@raeq
raeq / strings_17_csv.py
Last active July 23, 2020 20:57
List from csv line
def from_csv_line(line: str = "") -> list:
return line.split(",")
assert from_csv_line("a,b,c") == ["a", "b", "c"]