Skip to content

Instantly share code, notes, and snippets.

@capjamesg
Last active October 9, 2022 19:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save capjamesg/ea13ffae49a0c96c6a0b78c7a2798b47 to your computer and use it in GitHub Desktop.
Save capjamesg/ea13ffae49a0c96c6a0b78c7a2798b47 to your computer and use it in GitHub Desktop.
# draft of autotag function for use in indieweb-utils
import re
def _match_tag(tag_prefix: str, match: re.Match, user_tags: dict) -> str:
"""
Match a tag and return a link to the tag page.
:param tag_prefix: The prefix to append to the tag.
:type tag_prefix: str
:param match: The match to process.
:type match: re.Match
:param user_tags: A dictionary of tags that a user supports on their website.
:type user_tags: dict
:return: The processed match.
:rtype: str
"""
tag = match[1:]
if tag in user_tags:
return f"<a href='{tag_prefix}{tag}'>#{tag}</a>"
else:
return match
def _match_person_tag(people: dict, match: re.Match) -> str:
"""
A person tag and return a link to their profile.
:param people: A dictionary of names to which a person tag can be matched.
:type people: dict
:param match: The match to process.
:type match: re.Match
:return: The processed match.
:rtype: str
"""
person = match[1:]
if people.get(person):
return f"<a href='{people[person][0]}'>@{people[person][1]}</a>"
else:
return match
def autolink_tags(text: str, tag_prefix: str, people: dict, tags: list = []) -> str:
"""
Replace hashtags (#) and person tags (@) with links to the respective tag page and profile URL.
:param text: The text to process.
:type text: str
:param tag_prefix: The prefic to append to identified tags.
:type tag_prefix: str
:param people: A dictionary of people to link to.
:type people: dict
:param tags: A list of tags to link to (optional).
:type tags: list
:return: The processed text.
:rtype: str
Example:
..code-block:: python
import indieweb_utils
note = "I am working on a new #muffin #recipe with @jane"
people = {
"jane": ("Jane Doe", "https://jane.example.com") # tag to use, name of person, domain of person
}
note_with_tags = indieweb_utils.autolink_tags(note, "/tag/", people, tags=["muffin", "recipe"])
"""
user_supplied_tags = {tag: tag for tag in tags}
text = re.sub(r"#(\w+)", lambda match: _match_tag(tag_prefix, match.group(), user_supplied_tags), text)
text = re.sub(r"@(\w+)", lambda match: _match_person_tag(people, match.group()), text)
return text
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment