當前位置: 首頁>>代碼示例>>Python>>正文


Python typing.Match方法代碼示例

本文整理匯總了Python中typing.Match方法的典型用法代碼示例。如果您正苦於以下問題:Python typing.Match方法的具體用法?Python typing.Match怎麽用?Python typing.Match使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在typing的用法示例。


在下文中一共展示了typing.Match方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: check_if_removed_from_bugblog

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Match [as 別名]
def check_if_removed_from_bugblog(bbt: Match, b: Tag, issue: Issue) -> None:
    if bbt is not None:
        text = strings.remove_smartquotes(bbt.group(1).strip())
        for row in b.find_all('tr'):
            data = row.find_all('td')
            rowtext = strings.remove_smartquotes(data[1].text.strip())
            if rowtext == text:
                break
            if strip_squarebrackets(rowtext) == strip_squarebrackets(text):
                # Fix this
                print("Issue #{id}'s bug blog text has differing autocard notation.".format(id=issue.number))
                old_bbt = strings.get_body_field(issue.body, 'Bug Blog Text')
                body = re.sub(BBT_REGEX, 'Bug Blog Text: {0}'.format(rowtext), issue.body, flags=re.MULTILINE)
                new_bbt = strings.get_body_field(body, 'Bug Blog Text')
                issue.edit(body=body)
                print('Updated to `{0}`'.format(rowtext))
                issue.create_comment(f'Changed bug blog text from `{old_bbt}` to `{new_bbt}`')
                break
        else:
            print('{id} is fixed!'.format(id=issue.number))
            repo.create_comment(issue, 'This bug has been removed from the bug blog!')
            issue.edit(state='closed') 
開發者ID:PennyDreadfulMTG,項目名稱:Penny-Dreadful-Tools,代碼行數:24,代碼來源:scrape_bugblog.py

示例2: sub

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Match [as 別名]
def sub(cls, text: str, extension: str, replacers: Dict[str, Any]) -> str:
        found: Set[str] = set()
        kwargs = {x: _convert_to_string(y, extension) for x, y in replacers.items()}

        def _replacer(regex: Match[str]) -> str:
            name = regex.group("name")
            if name in found:
                raise RuntimeError(f'Trying to remplace a second time placeholder "{name}"')
            if name not in kwargs:
                raise KeyError(f'Could not find a value for placeholder "{name}"')
            found.add(name)
            return str(kwargs[name])

        text = re.sub(cls.pattern, _replacer, text)
        missing = set(kwargs) - found
        if missing:
            raise RuntimeError(f"All values have not been consumed: {missing}")
        return text 
開發者ID:facebookresearch,項目名稱:nevergrad,代碼行數:20,代碼來源:instantiate.py

示例3: process_not_inferred_dtype

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Match [as 別名]
def process_not_inferred_dtype(ex: pa.ArrowInvalid) -> pa.DataType:
    """Infer data type from PyArrow inference exception."""
    ex_str = str(ex)
    _logger.debug("PyArrow was not able to infer data type:\n%s", ex_str)
    match: Optional[Match] = re.search(
        pattern="Could not convert (.*) with type (.*): did not recognize "
        "Python value type when inferring an Arrow data type",
        string=ex_str,
    )
    if match is None:
        raise ex  # pragma: no cover
    groups: Optional[Sequence[str]] = match.groups()
    if groups is None:
        raise ex  # pragma: no cover
    if len(groups) != 2:
        raise ex  # pragma: no cover
    _logger.debug("groups: %s", groups)
    type_str: str = groups[1]
    if type_str == "UUID":
        return pa.string()
    raise ex  # pragma: no cover 
開發者ID:awslabs,項目名稱:aws-data-wrangler,代碼行數:23,代碼來源:_data_types.py

示例4: replace_with_safe_phrase

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Match [as 別名]
def replace_with_safe_phrase(matchobj: Match[str]) -> str:
    """
    The idea is to convert IGNORED_PHRASES into safe phrases, see
    `get_safe_phrase()` function. The only exception is when the
    IGNORED_PHRASE is at the start of the text or after a split
    boundary; in this case, we change the first letter of the phrase
    to upper case.
    """
    ignored_phrase = matchobj.group(0)
    safe_string = get_safe_phrase(ignored_phrase)

    start_index = matchobj.start()
    complete_string = matchobj.string

    is_string_start = start_index == 0
    # We expect that there will be one space between split boundary
    # and the next word.
    punctuation = complete_string[max(start_index - 2, 0)]
    is_after_split_boundary = punctuation in SPLIT_BOUNDARY
    if is_string_start or is_after_split_boundary:
        return safe_string.capitalize()

    return safe_string 
開發者ID:zulip,項目名稱:zulip,代碼行數:25,代碼來源:capitalization.py

示例5: colorFormat

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Match [as 別名]
def colorFormat(m: Match) -> str:
		color = m.group(1).title()

		if color == 'red':
			code = BashStringFormatCode.RED.value
		elif color == 'green':
			code = BashStringFormatCode.GREEN.value
		elif color == 'yellow':
			code = BashStringFormatCode.YELLOW.value
		elif color == 'blue':
			code = BashStringFormatCode.BLUE.value
		elif color == 'grey':
			code = BashStringFormatCode.GREY.value
		else:
			code = BashStringFormatCode.DEFAULT.value

		return BashStringFormatCode.SEQUENCE.value.format(code, m.group(2), BashStringFormatCode.DEFAULT) 
開發者ID:project-alice-assistant,項目名稱:ProjectAlice,代碼行數:19,代碼來源:BashFormatting.py

示例6: ytplaylist_url

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Match [as 別名]
def ytplaylist_url(match: Match[str]) -> str:
    location = match.group(4).split("=")[-1]
    request = get_playlist(location, ["contentDetails", "snippet"])
    raise_api_errors(request)

    json = request.json()

    data = json["items"]
    if not data:
        raise NoResultsError()

    item = data[0]
    snippet = item["snippet"]
    content_details = item["contentDetails"]

    title = snippet["title"]
    author = snippet["channelTitle"]
    num_videos = int(content_details["itemCount"])
    count_videos = " - \x02{:,}\x02 video{}".format(num_videos, "s"[num_videos == 1 :])
    return "\x02{}\x02 {} - \x02{}\x02".format(title, count_videos, author) 
開發者ID:TotallyNotRobots,項目名稱:CloudBot,代碼行數:22,代碼來源:youtube.py

示例7: _doc_class_replace

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Match [as 別名]
def _doc_class_replace(self, match: Match) -> str:
        """Build the sphinx doc class import

        :param match:
            The regex match for the given interface class.
        :returns:
            The string corresponding to the sphinx formatted class.
        """
        interface_name = match.group("interface")
        interface_class = "".join(x.capitalize() for x in interface_name.split("_"))

        if interface_name == self._interface_name:
            return ":class:`{}`".format(interface_class)

        if (
            self._interface_imports is not None
            and interface_name in self._interface_imports
        ):
            protocol_path = self._interface_imports[interface_name]
            return ":class:`~{base_path}.{iface}.{class_name}`".format(
                class_name=interface_class, base_path=BASE_PATH, iface=protocol_path,
            )

        return "`{}`".format(interface_class) 
開發者ID:flacjacket,項目名稱:pywayland,代碼行數:26,代碼來源:printer.py

示例8: test_any_is_subclass

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Match [as 別名]
def test_any_is_subclass(self):
        # Any should be considered a subclass of everything.
        assert issubclass(Any, Any)
        assert issubclass(Any, typing.List)
        assert issubclass(Any, typing.List[int])
        assert issubclass(Any, typing.List[T])
        assert issubclass(Any, typing.Mapping)
        assert issubclass(Any, typing.Mapping[str, int])
        assert issubclass(Any, typing.Mapping[KT, VT])
        assert issubclass(Any, Generic)
        assert issubclass(Any, Generic[T])
        assert issubclass(Any, Generic[KT, VT])
        assert issubclass(Any, AnyStr)
        assert issubclass(Any, Union)
        assert issubclass(Any, Union[int, str])
        assert issubclass(Any, typing.Match)
        assert issubclass(Any, typing.Match[str])
        # These expressions must simply not fail.
        typing.Match[Any]
        typing.Pattern[Any]
        typing.IO[Any] 
開發者ID:Microvellum,項目名稱:Fluid-Designer,代碼行數:23,代碼來源:test_typing.py

示例9: test_basics

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Match [as 別名]
def test_basics(self):
        pat = re.compile('[a-z]+', re.I)
        assert issubclass(pat.__class__, Pattern)
        assert issubclass(type(pat), Pattern)
        assert issubclass(type(pat), Pattern[str])

        mat = pat.search('12345abcde.....')
        assert issubclass(mat.__class__, Match)
        assert issubclass(mat.__class__, Match[str])
        assert issubclass(mat.__class__, Match[bytes])  # Sad but true.
        assert issubclass(type(mat), Match)
        assert issubclass(type(mat), Match[str])

        p = Pattern[Union[str, bytes]]
        assert issubclass(Pattern[str], Pattern)
        assert issubclass(Pattern[str], p)

        m = Match[Union[bytes, str]]
        assert issubclass(Match[bytes], Match)
        assert issubclass(Match[bytes], m) 
開發者ID:Microvellum,項目名稱:Fluid-Designer,代碼行數:22,代碼來源:test_typing.py

示例10: test_errors

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Match [as 別名]
def test_errors(self):
        with self.assertRaises(TypeError):
            # Doesn't fit AnyStr.
            Pattern[int]
        with self.assertRaises(TypeError):
            # Can't change type vars?
            Match[T]
        m = Match[Union[str, bytes]]
        with self.assertRaises(TypeError):
            # Too complicated?
            m[str]
        with self.assertRaises(TypeError):
            # We don't support isinstance().
            isinstance(42, Pattern)
        with self.assertRaises(TypeError):
            # We don't support isinstance().
            isinstance(42, Pattern[str]) 
開發者ID:Microvellum,項目名稱:Fluid-Designer,代碼行數:19,代碼來源:test_typing.py

示例11: _handle_message

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Match [as 別名]
def _handle_message(self, result: Match[bytes]) -> None:
        message_data = result.groupdict()

        message_payload_size = int(message_data["size"])
        message_payload = self._readline(size=message_payload_size)
        message_payload = self._strip(message_payload)

        message = NATSMessage(
            sid=int(message_data["sid"].decode()),
            subject=message_data["subject"].decode(),
            reply=message_data["reply"].decode() if message_data["reply"] else "",
            payload=message_payload,
        )

        sub = self._subs[message.sid]
        sub.received_messages += 1

        if sub.is_wasted():
            self._subs.pop(sub.sid)

        sub.callback(message) 
開發者ID:Gr1N,項目名稱:nats-python,代碼行數:23,代碼來源:client.py

示例12: _toFloatConversion

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Match [as 別名]
def _toFloatConversion(value: str) -> float:
    """Conversion of string to float."""

    value = value.replace(",", ".")
    """Ensure that all , are replaced with . (so they are seen as floats)"""

    def stripLeading0(matchobj: Match[str]) -> str:
        return matchobj.group(0).lstrip("0")

    regex_pattern = r"(?<!\.|\w|\d)0+(\d+)"
    """Literal eval does not like "02" as a value, but users see this as "2"."""
    """We therefore look numbers with leading "0", provided they are not used in variable names"""
    """example: "test02 * 20" should not be changed, but "test * 02 * 20" should be changed (into "test * 2 * 20")"""
    value = re.sub(regex_pattern, stripLeading0, value)

    try:
        return ast.literal_eval(value)
    except:
        return 0 
開發者ID:Ultimaker,項目名稱:Uranium,代碼行數:21,代碼來源:SettingDefinition.py

示例13: _replace_closure

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Match [as 別名]
def _replace_closure(replacement: str, m: Match[str]) -> str:
    def _replace_group(index: int) -> str:
        before = m.span(index)[0] - m.span()[0]
        after = m.span(index)[1] - m.span()[0]
        group = m.group()
        return group[:before] + replacement + group[after:]

    if m.group('in_double_quotes') is not None:
        return _replace_group(2)

    if m.group('in_single_quotes') is not None:
        return _replace_group(3)

    if m.group('plain_value') is not None:
        return _replace_group(4)

    assert False, m 
開發者ID:telepresenceio,項目名稱:telepresence,代碼行數:19,代碼來源:output_mask.py

示例14: search

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Match [as 別名]
def search(self, path: str) -> Optional[Match[str]]:
        if not self.matcher:
            return None
        return self.matcher.search(path) 
開發者ID:python,項目名稱:typeshed,代碼行數:6,代碼來源:pytype_test.py

示例15: decode_routing_key

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Match [as 別名]
def decode_routing_key(cls, encoded_routing_key: str) -> str:
        def decode(match: Match) -> str:
            return binascii.unhexlify(match.group(1).encode('utf-8')).decode('utf-8')

        return re.sub(r'___([a-f0-9]{2}|[a-f0-9]{4}|[a-f0-9]{6}|[a-f0-9]{8})_', decode, encoded_routing_key) 
開發者ID:kalaspuff,項目名稱:tomodachi,代碼行數:7,代碼來源:amqp.py


注:本文中的typing.Match方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。