Esempio n. 1
0
    def pretty_print(
        self,
        fmt: Union[None, str, TableFormat] = None,
        *,
        to: Optional[PathLike] = None,
        mode: str = "w",
        **kwargs,
    ) -> str:
        """
        Outputs a pretty table using the `tabulate <https://pypi.org/project/tabulate/>`_ package.

        Args:
            fmt: A tabulate format; if None, chooses according to ``to``, falling back to ``"plain"``
            to: Write to this path (.gz, .zip, etc. is inferred)
            mode: Write mode: 'w', 'a', or 'x'
            kwargs: Passed to tabulate

        Returns:
            The formatted string
        """
        fmt = Utils.choose_table_format(path=to, fmt=fmt)
        s = self._tabulate(fmt, **kwargs)
        if to is not None:
            Utils.write(to, s, mode=mode)
        return s
Esempio n. 2
0
 def to_rst(self,
            path_or_none: Optional[PathLike] = None,
            style: str = "simple",
            mode: str = "w") -> Optional[str]:
     """
     Writes a reStructuredText table.
     Args:
         path_or_none: Either a file path or ``None`` to return the string
         style: The type of table; currently only "simple" is supported
         mode: Write mode
     """
     txt = self._tabulate(fmt="rst") + "\n"
     return Utils.write(path_or_none, txt, mode=mode)
 def _to_properties_like(
     self,
     escape_keys,
     escape_values,
     sep: str,
     comment_char: str,
     path_or_buff=None,
     mode: str = "w",
     comment: Union[None, str, Sequence[str]] = None,
     **kwargs,
 ) -> Optional[str]:
     r"""
     Writes a .properties-like file.
     """
     comment = [] if comment is None else (
         [comment] if isinstance(comment, str) else comment)
     self.__class__._assert_can_write_properties_class()
     self._assert_can_write_properties_instance()
     df = self.vanilla_reset()
     if len(self.__class__.get_typing().required_names) == 2:
         key_col, val_col = self.__class__.get_typing().required_names
     else:
         key_col, val_col = "key", "value"
     df.columns = [key_col, val_col]
     df = df.sort_values(key_col)  # essential
     lines = [
         comment_char.lstrip(comment_char).lstrip() + " " + c
         for c in comment
     ]
     section = ""
     for k, v in zip(df[key_col], df[val_col]):
         if "." in k:
             k, s = str(k).split(".", 1)
             s, k = k.strip(), s.strip()
             if s != section:
                 lines.append(f"[{s}]")
         if escape_keys:
             k = escape_keys(k)
         if escape_values:
             v = escape_values(v)
         lines.append(k + " " + sep + " " + v.strip('"'))
     return Utils.write(path_or_buff,
                        os.linesep.join(lines),
                        mode=mode,
                        **kwargs)
Esempio n. 4
0
    def to_fwf(
        self,
        path_or_buff=None,
        mode: str = "w",
        colspecs: Optional[Sequence[Tuple[int, int]]] = None,
        widths: Optional[Sequence[int]] = None,
        na_rep: Optional[str] = None,
        float_format: Optional[str] = None,
        date_format: Optional[str] = None,
        decimal: str = ".",
        **kwargs,
    ) -> Optional[str]:
        """
        Writes a fixed-width text format.
        See ``read_fwf`` and ``to_flexwf`` for more info.

        .. warning:

            This method is a preview. Not all options are complete, and
            behavior is subject to change in a future (major) version.
            Notably, Pandas may eventually introduce a method with the same name.

        Args:
            path_or_buff: Path or buffer
            mode: write or append (w/a)
            colspecs: A list of tuples giving the extents of the fixed-width fields of each line
                      as half-open intervals (i.e., [from, to[ )
            widths: A list of field widths which can be used instead of ``colspecs``
                   if the intervals are contiguous
            na_rep: Missing data representation
            float_format: Format string for floating point numbers
            date_format: Format string for datetime objects
            decimal: Character recognized as decimal separator. E.g. use ‘,’ for European data.
            kwargs: Passed to :meth:`typeddfs.utils.Utils.write`

        Returns:
            The string data if ``path_or_buff`` is a buffer; None if it is a file
        """
        if colspecs is not None and widths is not None:
            raise ValueError("Both widths and colspecs passed")
        if widths is not None:
            colspecs = []
            at = 0
            for w in widths:
                colspecs.append((at, at + w))
                at += w
        # if colspecs is None:
        if True:
            # TODO: use format, etc.
            content = self._tabulate(Utils.plain_table_format(sep=" "),
                                     disable_numparse=True)
        else:
            df = self.vanilla_reset()
            if len(df.columns) != len(colspecs):
                raise ValueError(
                    f"{colspecs} column intervals for {len(df.columns)} columns"
                )
            for col, (start, end) in zip(df.columns, colspecs):
                width = end - start
                mx = df[col].map(str).map(len).max()
                if mx > width:
                    raise ValueError(
                        f"Column {col} has max length {mx} > {end-start}")
            _number_format = {
                "na_rep": na_rep,
                "float_format": float_format,
                "date_format": date_format,
                "quoting": csv.QUOTE_NONE,
                "decimal": decimal,
            }
            res = df._mgr.to_native_types(**_number_format)
            data: Sequence[Sequence[Any]] = [
                res.iget_values(i) for i in range(len(res.items))
            ]
            content = None  # TODO
        if path_or_buff is None:
            return content
        _encoding = dict(
            encoding=kwargs.get("encoding")) if "encoding" in kwargs else {}
        _compression = dict(encoding=kwargs.get(
            "compression")) if "compression" in kwargs else {}
        Utils.write(path_or_buff,
                    content,
                    mode=mode,
                    **_encoding,
                    **_compression)