Last active
December 25, 2019 22:44
-
-
Save mikeckennedy/3358f0908a39ae4872e9985b4f582aed to your computer and use it in GitHub Desktop.
Short script to take a string in the clipboard and replace it with something appropriate for a folder, file, or URL name.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Make sure to pip install pyperclip and colorama. | |
# Because output is better with color! | |
import pyperclip | |
from colorama import Fore | |
def main(): | |
print(Fore.WHITE + "-----------------------------") | |
print(Fore.WHITE + " URLIFY ") | |
print(Fore.WHITE + "-----------------------------") | |
print() | |
print(Fore.LIGHTCYAN_EX + "Reading data from clipboard...", flush=True) | |
try: | |
text = pyperclip.paste() | |
if not text or not text.strip(): | |
print(Fore.LIGHTRED_EX + "⚠️ ERROR: No data available in clipboard. 😢") | |
return | |
if len(text) > 300: | |
print(Fore.LIGHTRED_EX + f"⚠️ ERROR: The text was really long, too long: {len(text):,}...") | |
return | |
url_text = to_url_style(text) | |
print(Fore.WHITE + f"Original '{text}'") | |
print(Fore.LIGHTYELLOW_EX + "Converted text to " + Fore.LIGHTGREEN_EX + f"'{url_text}' 🌟🌟🌟✨") | |
pyperclip.copy(url_text) | |
print(Fore.WHITE + "Copied to clipboard 📋") | |
except Exception as x: | |
print(f"⚠️⚠️⚠️⚠️ Error: Unexpected crash: {x}.") | |
def to_url_style(text): | |
if not text: | |
return text | |
text = text.strip() | |
url_txt = '' | |
for ch in text: | |
url_txt += ch if ch.isalnum() or ch == '.' else ' ' | |
count = -1 | |
while count != len(url_txt): | |
count = len(url_txt) | |
url_txt = url_txt.strip() | |
url_txt = url_txt.replace(' ', ' ') | |
url_txt = url_txt.replace(' ', '-') | |
url_txt = url_txt.replace('--', '-') | |
return url_txt.lower().strip() | |
if __name__ == '__main__': | |
main() |
Hi @Hultner, sorry about that. Didn't realize it had that dependency. I just "inlined" that function into the script (edited).
Best,
Michael
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Do you have a link to
from talk_python_training.infrastructure.webutils import to_url_style
?Or maybe in-line it of it’s a simple function?