utils.py 文件源码

python
阅读 20 收藏 0 点赞 0 评论 0

项目:pcbot 作者: pckv 项目源码 文件源码
def split(text: str, maxsplit: int=-1):
    """ Split a string with shlex when possible, and add support for maxsplit.

    :param text: Text to split.
    :param maxsplit: Number of times to split. The rest is returned without splitting.
    :return: list: split text.
    """
    # Generate a shlex object for eventually splitting manually
    split_object = shlex.shlex(text, posix=True)
    split_object.quotes = '"`'
    split_object.whitespace_split = True
    split_object.commenters = ""

    # When the maxsplit is disabled, return the entire split object
    if maxsplit == -1:
        try:
            return list(split_object)
        except ValueError:  # If there is a problem with quotes, use the regular split method
            return text.split()

    # Create a list for the following split keywords
    maxsplit_object = []
    splits = 0

    # Split until we've reached the limit
    while splits < maxsplit:
        maxsplit_object.append(next(split_object))
        splits += 1

    # Add any following text without splitting
    maxsplit_object.append(split_object.instream.read())
    return maxsplit_object
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号