当前位置: 首页>>代码示例>>Python>>正文


Python re.split方法代码示例

本文整理汇总了Python中re.split方法的典型用法代码示例。如果您正苦于以下问题:Python re.split方法的具体用法?Python re.split怎么用?Python re.split使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在re的用法示例。


在下文中一共展示了re.split方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: write_version_py

# 需要导入模块: import re [as 别名]
# 或者: from re import split [as 别名]
def write_version_py():
    content = """# GENERATED VERSION FILE
# TIME: {}

__version__ = '{}'
short_version = '{}'
version_info = ({})
"""
    sha = get_hash()
    with open('mmdet/VERSION', 'r') as f:
        SHORT_VERSION = f.read().strip()
    VERSION_INFO = ', '.join(SHORT_VERSION.split('.'))
    VERSION = SHORT_VERSION + '+' + sha

    version_file_str = content.format(time.asctime(), VERSION, SHORT_VERSION,
                                      VERSION_INFO)
    with open(version_file, 'w') as f:
        f.write(version_file_str) 
开发者ID:open-mmlab,项目名称:mmdetection,代码行数:20,代码来源:setup.py

示例2: make_cuda_ext

# 需要导入模块: import re [as 别名]
# 或者: from re import split [as 别名]
def make_cuda_ext(name, module, sources, sources_cuda=[]):

    define_macros = []
    extra_compile_args = {'cxx': []}

    if torch.cuda.is_available() or os.getenv('FORCE_CUDA', '0') == '1':
        define_macros += [('WITH_CUDA', None)]
        extension = CUDAExtension
        extra_compile_args['nvcc'] = [
            '-D__CUDA_NO_HALF_OPERATORS__',
            '-D__CUDA_NO_HALF_CONVERSIONS__',
            '-D__CUDA_NO_HALF2_OPERATORS__',
        ]
        sources += sources_cuda
    else:
        print(f'Compiling {name} without CUDA')
        extension = CppExtension
        # raise EnvironmentError('CUDA is required to compile MMDetection!')

    return extension(
        name=f'{module}.{name}',
        sources=[os.path.join(*module.split('.'), p) for p in sources],
        define_macros=define_macros,
        extra_compile_args=extra_compile_args) 
开发者ID:open-mmlab,项目名称:mmdetection,代码行数:26,代码来源:setup.py

示例3: find_test_path

# 需要导入模块: import re [as 别名]
# 或者: from re import split [as 别名]
def find_test_path(test_file):
    """Searches for the test file and returns the path if found
    As a default, the currend working directory is the top of the search.
    If a directory was provided as part of the argument, the directory will be
    joined with cwd unless it was an absolute path, in which case, the
    absolute path will be used instead. 
    """
    test_file += ".py"
    test_path = os.path.split(test_file)
    top = os.path.join(os.getcwd(), test_path[0])

    for (path, dirs, files) in os.walk(top):
        if test_path[1] in files:
            return  os.path.join(path, test_path[1])
    raise FileNotFoundError("Could not find " + test_path[1] + 
                            "in directory: " + top) 
开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:18,代码来源:flakiness_checker.py

示例4: basic_tokenizer

# 需要导入模块: import re [as 别名]
# 或者: from re import split [as 别名]
def basic_tokenizer(sentence):
  """Very basic tokenizer: split the sentence into a list of tokens."""
  words = []
  if old_style:
    for space_separated_fragment in sentence.strip().split():
      words.extend(re.split(_OLD_WORD_SPLIT, space_separated_fragment))
    return [w for w in words if w]
  for space_separated_fragment in sentence.strip().split():
    tokens = [t for t in re.split(_WORD_SPLIT, space_separated_fragment) if t]
    first_is_char = False
    for i, t in enumerate(tokens):
      if len(t) == 1 and t in _PUNCTUATION:
        tokens[i] = _CHAR_MARKER + t
        if i == 0:
          first_is_char = True
    if words and words[-1] != _SPACE and (first_is_char or is_char(words[-1])):
      tokens = [_SPACE] + tokens
    spaced_tokens = []
    for i, tok in enumerate(tokens):
      spaced_tokens.append(tokens[i])
      if i < len(tokens) - 1:
        if tok != _SPACE and not (is_char(tok) or is_char(tokens[i+1])):
          spaced_tokens.append(_SPACE)
    words.extend(spaced_tokens)
  return words 
开发者ID:ringringyi,项目名称:DOTA_models,代码行数:27,代码来源:wmt_utils.py

示例5: extract_fields_db2

# 需要导入模块: import re [as 别名]
# 或者: from re import split [as 别名]
def extract_fields_db2(obj, line, field_name_regex):
    line = '#'.join(re.split('\s*#', line))

    last_key = ''
    field_names = re.findall(field_name_regex, line)
    for field in reversed(field_names):
        split_at = line.find(field) + len(field)
        field_name = re.split('\s*:', field)[0]
        # don't overwrite existing fields
        if field_name in obj:
            continue
        else:
            obj[field_name] = ' '.join(line[split_at:].split())
            if not last_key:
                last_key = field_name
        line = line[:split_at - len(field)]
    return last_key 
开发者ID:insightfinder,项目名称:InsightAgent,代码行数:19,代码来源:reportMetrics.py

示例6: _parse_docstring

# 需要导入模块: import re [as 别名]
# 或者: from re import split [as 别名]
def _parse_docstring(self, docstring=''):
        """
        :param docstring:
        :return: (summary, description, schema)
        """
        summary, description, schema = None, None, dict()
        docstring = docstring.strip()

        if '---' in docstring:
            head, yml = re.split(r'\s*---+\s*\n', docstring)
            if yml:
                schema = self.yaml_load(yml) or dict()
        else:
            head = docstring

        if '\n' in head.strip():
            summary, description = map(lambda s: s.strip(), head.split('\n', 1))
        elif head:
            summary = head.strip()

        return summary, description, schema 
开发者ID:Arello-Mobile,项目名称:py2swagger,代码行数:23,代码来源:yamlparser.py

示例7: get_cipher_list

# 需要导入模块: import re [as 别名]
# 或者: from re import split [as 别名]
def get_cipher_list(encryption_mode):
    """
    Get list of ciphers from encryption mode.

    Example:
    get_cipher_list("psk2+tkip+aes") -> ["TKIP", "CCMP"]
    """
    parts = encryption_mode.lower().split('+')
    ciphers = []

    if "tkip" in parts:
        ciphers.append("TKIP")
    if "ccmp" in parts or "aes" in parts:
        ciphers.append("CCMP")

    if len(ciphers) == 0:
        # We need to enable at least one cipher. Most modes default to CCMP
        # except for wpa.
        if parts[0] == "wpa":
            ciphers.append("TKIP")
        else:
            ciphers.append("CCMP")

    return ciphers 
开发者ID:ParadropLabs,项目名称:Paradrop,代码行数:26,代码来源:wireless.py

示例8: __init__

# 需要导入模块: import re [as 别名]
# 或者: from re import split [as 别名]
def __init__(self, name, uiType, size, persistence, familyPrefix, uiParams, tableSize, prefixSymbol, line):
		self.name = name
		self.familyPrefix = familyPrefix or ""
		self.uiType = uiType
		self.prefixSymbol = prefixSymbol
		if self.uiType == "ui_text_edit":
			self.prefixSymbol = "@"
		self.uiParams = uiParams or ""
		self.numElements = size
		self.dimensionsString = size
		self.underscore = ""
		if "," in size:
			self.underscore = "_"
			self.numElements = "*".join(["(%s)" % dim for dim in size.split(",")])
		self.numElements = tryStringEval(self.numElements, line, "UI array size")
		self.persistence = persistence or ""
		self.tableSize = tableSize 
开发者ID:nojanath,项目名称:SublimeKSP,代码行数:19,代码来源:preprocessor_plugins.py

示例9: prefix_with_ns

# 需要导入模块: import re [as 别名]
# 或者: from re import split [as 别名]
def prefix_with_ns(name, namespaces, function_parameter_names=None, force_prefixing=False):
    if not namespaces:
        return name
    function_parameter_names = function_parameter_names or []
    ##name = name.replace('.', '__') # replace . by __

    if name[0] in variable_prefixes:
        prefix, unprefixed_name = name[0], name[1:]
    else:
        prefix, unprefixed_name = '', name

    # if the name consists of multiple parts (eg. myfamily.myvariable extract the first part - myfamily in this example)
    first_name_part = name.split('.')[0]

    # if built-in name or function parameter
    if (unprefixed_name in ksp_builtins.variables_unprefixed or
          name in ksp_builtins.functions or
          name in ksp_builtins.keywords or
          first_name_part in function_parameter_names) and not force_prefixing:
        return name # don't add prefix

    # add namespace to name
    return prefix + '.'.join(namespaces + [unprefixed_name]) 
开发者ID:nojanath,项目名称:SublimeKSP,代码行数:25,代码来源:ksp_compiler.py

示例10: multiRunPostProcessing

# 需要导入模块: import re [as 别名]
# 或者: from re import split [as 别名]
def multiRunPostProcessing(self, PPoutpath, folders):
        outtext = list()
        for folder in folders:
            lines = list()
            with open(os.path.join(folder,'NEIDinfo.txt'), 'r') as g: #Write to file
                lines = g.read().split('\n')[0:-1]
            lines2 = [line.split(',') for line in lines]
            try:
                lines2 = lines2.remove([''])
            except:
                pass
            lines3 = [','.join(line) for line in lines2 if float(line[1]) < 24764.0/6371.0]
            outtext.append('\n'.join(lines3))#OUTTEXT contains a complete list of all sub-neptune detections
        with open(os.path.join(PPoutpath,'NEIDallSubNeptunes.txt'), 'w') as g: #Write to file
            g.write('\n'.join(outtext))
        
        #### Count number of surveys analyzed
        NumAnalyzed = 0
        for folder in folders:
            pklfiles = glob.glob(os.path.join(folder,'*.pkl'))
            NumAnalyzed += len(pklfiles)
        with open(os.path.join(PPoutpath,'NEIDcountFilesAnalyzed.txt'), 'w') as g: #Write to file
            g.write(str(NumAnalyzed)) 
开发者ID:dsavransky,项目名称:EXOSIMS,代码行数:25,代码来源:collateAllUniqueDetections.py

示例11: gist_fetch

# 需要导入模块: import re [as 别名]
# 或者: from re import split [as 别名]
def gist_fetch(query, page_idx, total_items=1000):
    gist_url = "https://gist.github.com/search?utf8=%E2%9C%93&q={}&p={}"
    query = urllib.parse.quote(query)
    gists = []

    try:
        resp = requests.get(gist_url.format(query, page_idx))
        soup = bs4.BeautifulSoup(resp.text, 'html.parser')
        total_items = min(total_items, int(
            [x.text.split()[0] for x in soup.find_all('h3')
                if "gist results" in x.text][0].replace(',', '')))
        gists = [x.get("href") for x in soup.findAll(
                            "a", class_="link-overlay")]
    except IndexError:
        return {"data": None, "total_items": 0}

    return {"data": gists, "total_items": total_items} 
开发者ID:BishopFox,项目名称:GitGot,代码行数:19,代码来源:gitgot.py

示例12: get_max_word_length

# 需要导入模块: import re [as 别名]
# 或者: from re import split [as 别名]
def get_max_word_length(
    string, formatter=None
):  # type: (str, Optional[Formatter]) -> int
    if formatter is not None:
        string = formatter.remove_format(string)

    max_length = 0
    words = re.split("\s+", string)

    for word in words:
        max_length = max(max_length, get_string_length(word))

    return max_length 
开发者ID:sdispater,项目名称:clikit,代码行数:15,代码来源:string.py

示例13: get_max_line_length

# 需要导入模块: import re [as 别名]
# 或者: from re import split [as 别名]
def get_max_line_length(
    string, formatter=None
):  # type: (str, Optional[Formatter]) -> int
    if formatter is not None:
        string = formatter.remove_format(string)

    max_length = 0
    words = re.split("\n", string)

    for word in words:
        max_length = max(max_length, get_string_length(word))

    return max_length 
开发者ID:sdispater,项目名称:clikit,代码行数:15,代码来源:string.py

示例14: validate_hostname

# 需要导入模块: import re [as 别名]
# 或者: from re import split [as 别名]
def validate_hostname(hostname):
    if len(hostname) > 255:
        raise Exception("Hostname {} is longer than 255 characters".format(hostname))
    if hostname[-1] == ".":
        hostname = hostname[:-1]
    allowed = re.compile(r"(?!-)[A-Z\d-]{1,63}(?<!-)$", re.IGNORECASE)
    if not all(allowed.match(x) for x in hostname.split(".")):
        raise Exception("Hostname {} is not RFC 1123 compliant".format(hostname)) 
开发者ID:kislyuk,项目名称:aegea,代码行数:10,代码来源:__init__.py

示例15: natural_sort

# 需要导入模块: import re [as 别名]
# 或者: from re import split [as 别名]
def natural_sort(i):
    return sorted(i, key=lambda s: [int(t) if t.isdigit() else t.lower() for t in re.split(r"(\d+)", s)]) 
开发者ID:kislyuk,项目名称:aegea,代码行数:4,代码来源:__init__.py


注:本文中的re.split方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。