当前位置: 首页>>代码示例>>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;未经允许,请勿转载。