Python add suffix

33 Python code examples are found related to " add suffix". You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: fr.py    From pynlg with MIT License 6 votes vote down vote up
def add_suffix(self, radical, suffix):
        """Return the concatenation of the radical, any appropriate
        liaison letters and the suffix.

        """
        # change "c" to "ç" and "g" to "ge" before "a" and "o";
        if re.match(self.a_o_regex, suffix):
            if radical.endswith(u'c'):
                radical = '%s%s' % (radical[:-1], u'ç')
            elif radical.endswith(u'g'):
                radical = '%s%s' % (radical, u'e')
        # if suffix begins with mute "e"
        elif suffix != u'ez' and suffix.startswith(u'e'):
            #  change "y" to "i" if not in front of "e"
            if not radical.endswith(u"ey") and radical.endswith(u"y"):
                radical = '%s%s' % (radical[:-1], u'i')
            #  change "e" and "é" to "è" in last sillable of radical
            if radical[-2] in [u'e', u'é']:
                radical = '%s%s%s' % (radical[:-2], u'é', radical[-1])
        return '%s%s' % (radical, suffix) 
Example 2
Source File: hererocks.py    From hererocks with MIT License 6 votes vote down vote up
def add_options_to_version_suffix(self):
        options = []

        if os.name == "nt" or opts.target != get_default_lua_target():
            options.append(("target", opts.target))

        if self.compat != "default":
            options.append(("compat", self.compat))

        if opts.cflags is not None:
            options.append(("cflags", opts.cflags))

        if opts.no_readline:
            options.append(("readline", "false"))

        if options:
            self.version_suffix += " (" + (", ".join(
                opt + ": " + value for opt, value in options)) + ")" 
Example 3
Source File: data.py    From modin with Apache License 2.0 6 votes vote down vote up
def add_suffix(self, suffix, axis):
        """Add a suffix to the current row or column labels.

        Args:
            suffix: The suffix to add.
            axis: The axis to update.

        Returns:
            A new dataframe with the updated labels.
        """
        new_labels = self.axes[axis].map(lambda x: str(x) + str(suffix))
        new_frame = self.copy()
        if axis == 0:
            new_frame.index = new_labels
        else:
            new_frame.columns = new_labels
        return new_frame

    # END Metadata modification methods 
Example 4
Source File: css_default.py    From canvas with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def add_suffix(self, url):
        filename = self.guess_filename(url)
        suffix = None
        if filename:
            if settings.COMPRESS_CSS_HASHING_METHOD == "mtime":
                suffix = get_hashed_mtime(filename)
            elif settings.COMPRESS_CSS_HASHING_METHOD == "hash":
                hash_file = open(filename)
                try:
                    suffix = get_hexdigest(hash_file.read(), 12)
                finally:
                    hash_file.close()
            else:
                raise FilterError('COMPRESS_CSS_HASHING_METHOD is configured '
                                  'with an unknown method (%s).')
        if suffix is None:
            return url
        if url.startswith(('http://', 'https://', '/')):
            if "?" in url:
                url = "%s&%s" % (url, suffix)
            else:
                url = "%s?%s" % (url, suffix)
        return url 
Example 5
Source File: sct_utils.py    From spinalcordtoolbox with MIT License 6 votes vote down vote up
def add_suffix(fname, suffix):
    """
    Add suffix between end of file name and extension.

    :param fname: absolute or relative file name. Example: t2.nii
    :param suffix: suffix. Example: _mean
    :return: file name with suffix. Example: t2_mean.nii

    Examples:

    - add_suffix(t2.nii, _mean) -> t2_mean.nii
    - add_suffix(t2.nii.gz, a) -> t2a.nii.gz
    """
    parent, stem, ext = extract_fname(fname)
    return os.path.join(parent, stem + suffix + ext)


#=======================================================================================================================
# run
#=======================================================================================================================
# Run UNIX command 
Example 6
Source File: glm.py    From SAMRI with GNU General Public License v3.0 6 votes vote down vote up
def add_suffix(name, suffix):
	"""A function that adds suffix to a variable.

	Returns converted to string-type input variable 'name', and string-type converted variable
	'suffix' added at the end of 'name'.
	If variable 'name' is type list, all the elements are being converted to strings and
	they are being joined.

	Parameters
	----------
	name : list or str
		Will be converted to string and return with suffix
	suffix : str
		Will be converted to string and will be added at the end of 'name'.

	Returns
	-------
	str
		String type variable 'name' with suffix, the string variable 'suffix'.

	"""

	if type(name) is list:
		name = "".join([str(i) for i in name])
	return str(name)+str(suffix) 
Example 7
Source File: imputil.py    From RevitBatchProcessor with GNU General Public License v3.0 5 votes vote down vote up
def add_suffix(self, suffix, importFunc):
        assert hasattr(importFunc, '__call__')
        self.fs_imp.add_suffix(suffix, importFunc)

    ######################################################################
    #
    # PRIVATE METHODS
    # 
Example 8
Source File: __init__.py    From jx-sqlite with Mozilla Public License 2.0 5 votes vote down vote up
def add_suffix(self, suffix):
        """
        ADD suffix TO THE filename (NOT INCLUDING THE FILE EXTENSION)
        """
        return File(add_suffix(self._filename, suffix)) 
Example 9
Source File: build.py    From ConTroll_Remote_Access_Trojan with Apache License 2.0 5 votes vote down vote up
def addSuffixToExtensions(toc):
    """
    Returns a new TOC with proper library suffix for EXTENSION items.
    """
    new_toc = TOC()
    for inm, fnm, typ in toc:
        if typ in ('EXTENSION', 'DEPENDENCY'):
            binext = os.path.splitext(fnm)[1]
            if not os.path.splitext(inm)[1] == binext:
                inm = inm + binext
        new_toc.append((inm, fnm, typ))
    return new_toc


#--- functons for checking guts --- 
Example 10
Source File: humanize.py    From clgen with GNU General Public License v3.0 5 votes vote down vote up
def AddOrdinalSuffix(value):
  """Adds an ordinal suffix to a non-negative integer (e.g. 1 -> '1st').

  Args:
    value: A non-negative integer.

  Returns:
    A string containing the integer with a two-letter ordinal suffix.
  """
  if value < 0 or value != int(value):
    raise ValueError("argument must be a non-negative integer: %s" % value)

  if value % 100 in (11, 12, 13):
    suffix = "th"
  else:
    rem = value % 10
    if rem == 1:
      suffix = "st"
    elif rem == 2:
      suffix = "nd"
    elif rem == 3:
      suffix = "rd"
    else:
      suffix = "th"

  return str(value) + suffix 
Example 11
Source File: misc.py    From niworkflows with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def add_suffix(in_files, suffix):
    """
    Wrap nipype's fname_presuffix to conveniently just add a prefix

    >>> add_suffix([
    ...     '/path/to/sub-045_ses-test_T1w.nii.gz',
    ...     '/path/to/sub-045_ses-retest_T1w.nii.gz'], '_test')
    'sub-045_ses-test_T1w_test.nii.gz'

    """
    import os.path as op
    from nipype.utils.filemanip import fname_presuffix, filename_to_list

    return op.basename(fname_presuffix(filename_to_list(in_files)[0], suffix=suffix)) 
Example 12
Source File: scanner.py    From seedsync with Apache License 2.0 5 votes vote down vote up
def add_exclude_suffix(self, suffix: str):
        """
        Exclude files that end with the given suffix
        :param suffix:
        :return:
        """
        self.exclude_suffixes.append(suffix) 
Example 13
Source File: image.py    From gee_tools with MIT License 5 votes vote down vote up
def addSuffix(image, suffix, bands=None):
    """ Add a suffix to the specified bands

    :param suffix: the value to add as a suffix
    :type suffix: str
    :param bands: the bands to apply the suffix. If None, suffix will fill
        all bands
    :type bands: list
    :rtype: ee.Image
    """
    return _add_suffix_prefix(image, suffix, 'suffix', bands) 
Example 14
Source File: ArnoldDenoiser.py    From sitoa with Apache License 2.0 5 votes vote down vote up
def addFilebaseSuffix(self, suffix):
        if self.filebase[-1] in u'._':
            new_filebase = self.filebase[:-1]
            new_filebase += suffix
            new_filebase += self.filebase[-1:]
        else:
            new_filebase = self.filebase + suffix
            
        self.filebase = new_filebase 
Example 15
Source File: empty_vs_non_empty.py    From open-solution-salt-identification with MIT License 5 votes vote down vote up
def add_fold_id_suffix(config, fold_id):
    config['model']['network']['callbacks_config']['neptune_monitor']['model_name'] = 'network_{}'.format(fold_id)
    checkpoint_filepath = config['model']['network']['callbacks_config']['model_checkpoint']['filepath']
    fold_checkpoint_filepath = checkpoint_filepath.replace('network/best.torch',
                                                           'network_{}/best.torch'.format(fold_id))
    config['model']['network']['callbacks_config']['model_checkpoint']['filepath'] = fold_checkpoint_filepath
    return config 
Example 16
Source File: humanize.py    From google-apputils with Apache License 2.0 5 votes vote down vote up
def AddOrdinalSuffix(value):
  """Adds an ordinal suffix to a non-negative integer (e.g. 1 -> '1st').

  Args:
    value: A non-negative integer.

  Returns:
    A string containing the integer with a two-letter ordinal suffix.
  """
  if value < 0 or value != int(value):
    raise ValueError('argument must be a non-negative integer: %s' % value)

  if value % 100 in (11, 12, 13):
    suffix = 'th'
  else:
    rem = value % 10
    if rem == 1:
      suffix = 'st'
    elif rem == 2:
      suffix = 'nd'
    elif rem == 3:
      suffix = 'rd'
    else:
      suffix = 'th'

  return str(value) + suffix 
Example 17
Source File: input_arparser.py    From NiftyMIC with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def add_suffix_mask(
        self,
        option_string="--suffix-mask",
        type=str,
        help="Suffix used to associate a mask with an image. "
        "E.g. suffix_mask='_mask' means an existing "
        "image_i_mask.nii.gz represents the mask to "
        "image_i.nii.gz for all images image_i in the input "
        "directory.",
        default="_mask",
        required=False,
    ):
        self._add_argument(dict(locals())) 
Example 18
Source File: train.py    From video_prediction with MIT License 5 votes vote down vote up
def add_tag_suffix(summary, tag_suffix):
    summary_proto = tf.Summary()
    summary_proto.ParseFromString(summary)
    summary = summary_proto

    for value in summary.value:
        tag_split = value.tag.split('/')
        value.tag = '/'.join([tag_split[0] + tag_suffix] + tag_split[1:])
    return summary.SerializeToString() 
Example 19
Source File: tensor.py    From tncontract with MIT License 5 votes vote down vote up
def add_suffix_to_labels(self, suffix):
        """Warning: by changing the labels, e.g. with this method, 
        the MPS will no longer be in the correct form for various MPS functions
        ."""
        new_labels = []
        for label in self.labels:
            new_labels.append(label + suffix)
        self.labels = new_labels 
Example 20
Source File: utils.py    From scrape with MIT License 5 votes vote down vote up
def add_url_suffix(url):
    """Add .com suffix to URL if none found."""
    url = url.rstrip("/")
    if not has_suffix(url):
        return "{0}.com".format(url)
    return url


# File processing functions
# 
Example 21
Source File: generic.py    From Computable with MIT License 5 votes vote down vote up
def add_suffix(self, suffix):
        """
        Concatenate suffix string with panel items names

        Parameters
        ----------
        suffix : string

        Returns
        -------
        with_suffix : type of caller
        """
        new_data = self._data.add_suffix(suffix)
        return self._constructor(new_data).__finalize__(self) 
Example 22
Source File: file_utils.py    From nucleus7 with Mozilla Public License 2.0 5 votes vote down vote up
def add_suffix(fname: str, suffix: str) -> str:
    """
    Add suffix fo filename just before extension

    Parameters
    ----------
    fname
        file name to add the suffix
    suffix
        suffix to add

    Returns
    -------
    fname_with_suffix
        file name with suffix

    Examples
    --------
    >>> add_suffix('file/name.ext', '_suffix')
    'file/name_suffix.ext'
    """
    fname_, ext = os.path.splitext(fname)
    return ''.join((fname_, suffix, ext)) 
Example 23
Source File: utils.py    From attacut with MIT License 5 votes vote down vote up
def add_suffix_to_file_path(path: str, suffix: str) -> str:
    dirname = os.path.dirname(path)
    basename = os.path.basename(path)
    filename, ext = basename.split('.')

    return os.path.join(dirname, "%s-%s.%s" % (filename, suffix, ext)) 
Example 24
Source File: series.py    From koalas with Apache License 2.0 4 votes vote down vote up
def add_suffix(self, suffix):
        """
        Suffix labels with string suffix.

        For Series, the row labels are suffixed.
        For DataFrame, the column labels are suffixed.

        Parameters
        ----------
        suffix : str
           The string to add after each label.

        Returns
        -------
        Series
           New Series with updated labels.

        See Also
        --------
        Series.add_prefix: Prefix row labels with string `prefix`.
        DataFrame.add_prefix: Prefix column labels with string `prefix`.
        DataFrame.add_suffix: Suffix column labels with string `suffix`.

        Examples
        --------
        >>> s = ks.Series([1, 2, 3, 4])
        >>> s
        0    1
        1    2
        2    3
        3    4
        Name: 0, dtype: int64

        >>> s.add_suffix('_item')
        0_item    1
        1_item    2
        2_item    3
        3_item    4
        Name: 0, dtype: int64
        """
        assert isinstance(suffix, str)
        internal = self.to_frame()._internal
        sdf = internal.spark_frame.select(
            [
                F.concat(index_spark_column, F.lit(suffix)).alias(index_spark_column_name)
                for index_spark_column, index_spark_column_name in zip(
                    internal.index_spark_columns, internal.index_spark_column_names
                )
            ]
            + internal.data_spark_columns
        )
        return first_series(DataFrame(internal.with_new_sdf(sdf))) 
Example 25
Source File: imphook2.py    From cloud-debug-python with Apache License 2.0 4 votes vote down vote up
def AddImportCallbackBySuffix(path, callback):
  """Register import hook.

  This function overrides the default import process. Then whenever a module
  whose suffix matches path is imported, the callback will be invoked.

  A module may be imported multiple times. Import event only means that the
  Python code contained an "import" statement. The actual loading and
  initialization of a new module normally happens only once, at which time
  the callback will be invoked. This function does not validates the existence
  of such a module and it's the responsibility of the caller.

  TODO: handle module reload.

  Args:
    path: python module file path. It may be missing the directories for the
          outer packages, and therefore, requires suffix comparison to match
          against loaded modules. If it contains all outer packages, it may
          contain the sys.path as well.
          It might contain an incorrect file extension (e.g., py vs. pyc).
    callback: callable to invoke upon module load.

  Returns:
    Function object to invoke to remove the installed callback.
  """

  def RemoveCallback():
    # This is a read-if-del operation on _import_callbacks. Lock to prevent
    # callbacks from being inserted just before the key is deleted. Thus, it
    # must be locked also when inserting a new entry below. On the other hand
    # read only access, in the import hook, does not require a lock.
    with _import_callbacks_lock:
      callbacks = _import_callbacks.get(path)
      if callbacks:
        callbacks.remove(callback)
        if not callbacks:
          del _import_callbacks[path]

  with _import_callbacks_lock:
    _import_callbacks.setdefault(path, set()).add(callback)
  _InstallImportHookBySuffix()

  return RemoveCallback