Skip to main content

Links recognition library with FULL unicode support.

Project description

linkify-it-py

CI pypi codecov Maintainability

This is Python port of linkify-it.

Links recognition library with FULL unicode support. Focused on high quality link patterns detection in plain text.

Javascript Demo

Why it's awesome:

  • Full unicode support, with astral characters!
  • International domains support.
  • Allows rules extension & custom normalizers.

Install

pip install linkify-it-py

Usage examples

Example 1. Simple use

from linkify_it import LinkifyIt


linkify = LinkifyIt()

print(linkify.test("Site github.com!"))
# => True

print(linkify.match("Site github.com!"))
# => [linkify_it.main.Match({
#         'schema': '',
#         'index': 5,
#         'last_index': 15,
#         'raw': 'github.com',
#         'text': 'github.com',
#         'url': 'http://github.com'
#     }]

Example 2. With options

from linkify_it import LinkifyIt
from linkify_it.tlds import TLDS


# Reload full tlds list & add unofficial `.onion` domain.
linkify = (
    LinkifyIt()
    .tlds(TLDS)               # Reload with full tlds list
    .tlds("onion", True)      # Add unofficial `.onion` domain
    .add("git:", "http:")     # Add `git:` protocol as "alias"
    .add("ftp:", None)        # Disable `ftp:` protocol
    .set({"fuzzy_ip": True})  # Enable IPs in fuzzy links (without schema)
)
print(linkify.test("Site tamanegi.onion!"))
# => True

print(linkify.match("Site tamanegi.onion!"))
# => [linkify_it.main.Match({
#         'schema': '',
#         'index': 5,
#         'last_index': 19,
#         'raw': 'tamanegi.onion',
#         'text': 'tamanegi.onion',
#         'url': 'http://tamanegi.onion'
#     }]

Example 3. Add twitter mentions handler

from linkify import LinkfiyIt


linkifyit = LinkifyIt()

def validate(self, text, pos):
    tail = text[pos:]

    if not self.re.get("twitter"):
        self.re["twitter"] = re.compile(
            "^([a-zA-Z0-9_]){1,15}(?!_)(?=$|" + self.re["src_ZPCc"] + ")"
        )
    if self.re["twitter"].search(tail):
        if pos > 2 and tail[pos - 2] == "@":
            return False
        return len(self.re["twitter"].search(tail).group())
    return 0

def normalize(self, m):
    m.url = "https://twitter.com/" + re.sub(r"^@", "", m.url)

linkifyit.add("@", {"validate": validate, "normalize": normalize})

API

API documentation

LinkifyIt(schemas, options)

Creates new linkifier instance with optional additional schemas.

By default understands:

  • http(s)://... , ftp://..., mailto:... & //... links
  • "fuzzy" links and emails (google.com, foo@bar.com).

schemas is an dict, where each key/value describes protocol/rule:

  • key - link prefix (usually, protocol name with : at the end, skype: for example). linkify-it-py makes sure that prefix is not preceded with alphanumeric char.
  • value - rule to check tail after link prefix
    • str
      • just alias to existing rule
    • dict
      • validate - either a re.Pattern (start with ^, and don't include the link prefix itself), or a validator function which, given arguments self, text and pos, returns the length of a match in text starting at index pos. pos is the index right after the link prefix. self can be used to access the linkify object to cache data.
      • normalize - optional function to normalize text & url of matched result (for example, for twitter mentions).

options:

  • fuzzy_link - recognize URL-s without http(s):// head. Default True.
  • fuzzy_ip - allow IPs in fuzzy links above. Can conflict with some texts like version numbers. Default False.
  • fuzzy_email - recognize emails without mailto: prefix. Default True.
  • --- - set True to terminate link with --- (if it's considered as long dash).

.test(text)

Searches linkifiable pattern and returns True on success or False on fail.

.pretest(text)

Quick check if link MAY BE can exist. Can be used to optimize more expensive .test() calls. Return False if link can not be found, True - if .test() call needed to know exactly.

.test_schema_at(text, name, position)

Similar to .test() but checks only specific protocol tail exactly at given position. Returns length of found pattern (0 on fail).

.match(text)

Returns list of found link matches or null if nothing found.

Each match has:

  • schema - link schema, can be empty for fuzzy links, or // for protocol-neutral links.
  • index - offset of matched text
  • last_index - index of next char after mathch end
  • raw - matched text
  • text - normalized text
  • url - link, generated from matched text

.tlds(list_tlds, keep_old=False)

Load (or merge) new tlds list. Those are needed for fuzzy links (without schema) to avoid false positives. By default:

  • 2-letter root zones are ok.
  • biz|com|edu|gov|net|org|pro|web|xxx|aero|asia|coop|info|museum|name|shop|рф are ok.
  • encoded (xn--...) root zones are ok.

If that's not enough, you can reload defaults with more detailed zones list.

.add(key, value)

Add a new schema to the schemas object. As described in the constructor definition, key is a link prefix (skype:, for example), and value is a str to alias to another schema, or an dict with validate and optionally normalize definitions. To disable an existing rule, use .add(key, None).

.set(options)

Override default options. Missed properties will not be changed.

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

linkify-it-py-1.0.0.tar.gz (23.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

linkify_it_py-1.0.0-py3-none-any.whl (19.5 kB view details)

Uploaded Python 3

File details

Details for the file linkify-it-py-1.0.0.tar.gz.

File metadata

  • Download URL: linkify-it-py-1.0.0.tar.gz
  • Upload date:
  • Size: 23.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.2.0 pkginfo/1.6.1 requests/2.25.0 setuptools/50.3.2 requests-toolbelt/0.9.1 tqdm/4.51.0 CPython/3.7.9

File hashes

Hashes for linkify-it-py-1.0.0.tar.gz
Algorithm Hash digest
SHA256 92fe76ad70ec6389e9b0445a3c6ab38f14f7e67859a4b61a765c09b62d284f91
MD5 3f5270ed40f230844d9708bc1037c92e
BLAKE2b-256 f556190806a3bd0b7495fdbacc2b0ce16a99b6e23e9b69aa95a25a98eb298ab2

See more details on using hashes here.

File details

Details for the file linkify_it_py-1.0.0-py3-none-any.whl.

File metadata

  • Download URL: linkify_it_py-1.0.0-py3-none-any.whl
  • Upload date:
  • Size: 19.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.2.0 pkginfo/1.6.1 requests/2.25.0 setuptools/50.3.2 requests-toolbelt/0.9.1 tqdm/4.51.0 CPython/3.7.9

File hashes

Hashes for linkify_it_py-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 b7109fc7784de1751cb7d481ecb7d9cc3de78054b66401e6f572d2f29caa44ac
MD5 fb8fcd17637166de7975eab023620572
BLAKE2b-256 e82d85c9abba58ee5a058202e332b3f0a1e3a103a5c6020a402e3a360916cca9

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page