當前位置: 首頁>>代碼示例>>Python>>正文


Python ascii.write方法代碼示例

本文整理匯總了Python中astropy.io.ascii.write方法的典型用法代碼示例。如果您正苦於以下問題:Python ascii.write方法的具體用法?Python ascii.write怎麽用?Python ascii.write使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在astropy.io.ascii的用法示例。


在下文中一共展示了ascii.write方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: test_write_table_html_fill_values_masked

# 需要導入模塊: from astropy.io import ascii [as 別名]
# 或者: from astropy.io.ascii import write [as 別名]
def test_write_table_html_fill_values_masked():
    """
    Test that passing masked values in fill_values should only replace
    masked columns or values
    """
    buffer_output = StringIO()
    t = Table([[1], [1]], names=('a', 'b'), masked=True, dtype=('i4', 'i8'))
    t['a'] = np.ma.masked
    ascii.write(t, buffer_output, fill_values=(ascii.masked, 'TEST'),
        format='html')

    t_expected = Table([['TEST'], [1]], names=('a', 'b'))
    buffer_expected = StringIO()
    ascii.write(t_expected, buffer_expected, format='html')

    assert buffer_output.getvalue() == buffer_expected.getvalue() 
開發者ID:holzschu,項目名稱:Carnets,代碼行數:18,代碼來源:test_html.py

示例2: test_multicolumn_table_html_fill_values

# 需要導入模塊: from astropy.io import ascii [as 別名]
# 或者: from astropy.io.ascii import write [as 別名]
def test_multicolumn_table_html_fill_values():
    """
    Test to make sure that the HTML writer writes multidimensional
    columns with correctly replaced fill_values.
    """
    col1 = [1, 2, 3]
    col2 = [(1.0, 1.0), (2.0, 2.0), (3.0, 3.0)]
    col3 = [('a', 'a', 'a'), ('b', 'b', 'b'), ('c', 'c', 'c')]

    buffer_output = StringIO()
    t = Table([col1, col2, col3], names=('C1', 'C2', 'C3'))
    ascii.write(t, buffer_output, fill_values=('a', 'z'),
        format='html')

    col1 = [1, 2, 3]
    col2 = [(1.0, 1.0), (2.0, 2.0), (3.0, 3.0)]
    col3 = [('z', 'z', 'z'), ('b', 'b', 'b'), ('c', 'c', 'c')]

    buffer_expected = StringIO()
    t_expected = Table([col1, col2, col3], names=('C1', 'C2', 'C3'))
    ascii.write(t_expected, buffer_expected, format='html')

    assert buffer_output.getvalue() == buffer_expected.getvalue() 
開發者ID:holzschu,項目名稱:Carnets,代碼行數:25,代碼來源:test_html.py

示例3: test_multi_column_write_table_html_fill_values_masked

# 需要導入模塊: from astropy.io import ascii [as 別名]
# 或者: from astropy.io.ascii import write [as 別名]
def test_multi_column_write_table_html_fill_values_masked():
    """
    Test that passing masked values in fill_values should only replace
    masked columns or values for multidimensional tables
    """
    buffer_output = StringIO()
    t = Table([[1, 2, 3, 4], ['--', 'a', '--', 'b']], names=('a', 'b'), masked=True)
    t['a'][0:2] = np.ma.masked
    t['b'][0:2] = np.ma.masked
    ascii.write(t, buffer_output, fill_values=[(ascii.masked, 'MASKED')],
        format='html')

    t_expected = Table([['MASKED', 'MASKED', 3, 4], ['MASKED', 'MASKED', '--', 'b']], names=('a', 'b'))
    buffer_expected = StringIO()
    ascii.write(t_expected, buffer_expected, format='html')
    print(buffer_expected.getvalue())

    assert buffer_output.getvalue() == buffer_expected.getvalue() 
開發者ID:holzschu,項目名稱:Carnets,代碼行數:20,代碼來源:test_html.py

示例4: test_too_long_comment

# 需要導入模塊: from astropy.io import ascii [as 別名]
# 或者: from astropy.io.ascii import write [as 別名]
def test_too_long_comment():
    with catch_warnings(UserWarning) as w:
        table = Table([[3]])
        table.meta['comments'] = ['a' * 79]
        out = StringIO()
        ascii.write(table, out, Writer=Ipac)
    w = w[0]
    assert 'Comment string > 78 characters was automatically wrapped.' == str(w.message)
    expected_out = """\
\\ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
\\ a
|col0|
|long|
|    |
|null|
    3
"""
    assert out.getvalue().strip().splitlines() == expected_out.splitlines() 
開發者ID:holzschu,項目名稱:Carnets,代碼行數:20,代碼來源:test_ipac_definitions.py

示例5: test_out_with_nonstring_null

# 需要導入模塊: from astropy.io import ascii [as 別名]
# 或者: from astropy.io.ascii import write [as 別名]
def test_out_with_nonstring_null():
    '''Test a (non-string) fill value.

    Even for an unmasked tables, the fill_value should show up in the
    table header.
    '''
    table = Table([[3]], masked=True)
    out = StringIO()
    ascii.write(table, out, Writer=Ipac, fill_values=[(masked, -99999)])
    expected_out = """\
|  col0|
|  long|
|      |
|-99999|
      3
"""
    assert out.getvalue().strip().splitlines() == expected_out.splitlines() 
開發者ID:holzschu,項目名稱:Carnets,代碼行數:19,代碼來源:test_ipac_definitions.py

示例6: check_write_table_via_table

# 需要導入模塊: from astropy.io import ascii [as 別名]
# 或者: from astropy.io.ascii import write [as 別名]
def check_write_table_via_table(test_def, table, fast_writer):
    out = StringIO()

    test_def = copy.deepcopy(test_def)
    if 'Writer' in test_def['kwargs']:
        format = 'ascii.{}'.format(test_def['kwargs']['Writer']._format_name)
        del test_def['kwargs']['Writer']
    else:
        format = 'ascii'

    try:
        table.write(out, format=format, fast_writer=fast_writer, **test_def['kwargs'])
    except ValueError as e:  # if format doesn't have a fast writer, ignore
        if 'not in the list of formats with fast writers' not in str(e.value):
            raise e
        return
    print('Expected:\n{}'.format(test_def['out']))
    print('Actual:\n{}'.format(out.getvalue()))
    assert [x.strip() for x in out.getvalue().strip().splitlines()] == [
        x.strip() for x in test_def['out'].strip().splitlines()] 
開發者ID:holzschu,項目名稱:Carnets,代碼行數:22,代碼來源:test_write.py

示例7: test_write_comments

# 需要導入模塊: from astropy.io import ascii [as 別名]
# 或者: from astropy.io.ascii import write [as 別名]
def test_write_comments(fast_writer):
    """Write comments in output originally read by io.ascii."""
    data = ascii.read('#c1\n  # c2\t\na,b,c\n#  c3\n1,2,3')
    out = StringIO()
    ascii.write(data, out, format='basic', fast_writer=fast_writer)
    expected = ['# c1', '# c2', '# c3', 'a b c', '1 2 3']
    assert out.getvalue().splitlines() == expected

    # header comes before comments for commented-header
    out = StringIO()
    ascii.write(data, out, format='commented_header', fast_writer=fast_writer)
    expected = ['# a b c', '# c1', '# c2', '# c3', '1 2 3']
    assert out.getvalue().splitlines() == expected

    # setting comment=False should disable comment writing
    out = StringIO()
    ascii.write(data, out, format='basic', comment=False, fast_writer=fast_writer)
    expected = ['a b c', '1 2 3']
    assert out.getvalue().splitlines() == expected 
開發者ID:holzschu,項目名稱:Carnets,代碼行數:21,代碼來源:test_write.py

示例8: test_write_read_roundtrip

# 需要導入模塊: from astropy.io import ascii [as 別名]
# 或者: from astropy.io.ascii import write [as 別名]
def test_write_read_roundtrip():
    """
    Write a full-featured table with all types and see that it round-trips on
    readback.  Use both space and comma delimiters.
    """
    t = T_DTYPES
    for delimiter in DELIMITERS:
        out = StringIO()
        t.write(out, format='ascii.ecsv', delimiter=delimiter)

        t2s = [Table.read(out.getvalue(), format='ascii.ecsv'),
                Table.read(out.getvalue(), format='ascii'),
                ascii.read(out.getvalue()),
                ascii.read(out.getvalue(), format='ecsv', guess=False),
                ascii.read(out.getvalue(), format='ecsv')]
        for t2 in t2s:
            assert t.meta == t2.meta
            for name in t.colnames:
                assert t[name].attrs_equal(t2[name])
                assert np.all(t[name] == t2[name]) 
開發者ID:holzschu,項目名稱:Carnets,代碼行數:22,代碼來源:test_ecsv.py

示例9: test_ecsv_mixins_ascii_read_class

# 需要導入模塊: from astropy.io import ascii [as 別名]
# 或者: from astropy.io.ascii import write [as 別名]
def test_ecsv_mixins_ascii_read_class():
    """Ensure that ascii.read(ecsv_file) returns the correct class
    (QTable if any Quantity subclasses, Table otherwise).
    """
    # Make a table with every mixin type except Quantities
    t = QTable({name: col for name, col in mixin_cols.items()
                if not isinstance(col.info, QuantityInfo)})
    out = StringIO()
    t.write(out, format="ascii.ecsv")
    t2 = ascii.read(out.getvalue(), format='ecsv')
    assert type(t2) is Table

    # Add a single quantity column
    t['lon'] = mixin_cols['lon']

    out = StringIO()
    t.write(out, format="ascii.ecsv")
    t2 = ascii.read(out.getvalue(), format='ecsv')
    assert type(t2) is QTable 
開發者ID:holzschu,項目名稱:Carnets,代碼行數:21,代碼來源:test_ecsv.py

示例10: test_round_trip_masked_table_serialize_mask

# 需要導入模塊: from astropy.io import ascii [as 別名]
# 或者: from astropy.io.ascii import write [as 別名]
def test_round_trip_masked_table_serialize_mask(tmpdir):
    """Same as prev but set the serialize_method to 'data_mask' so mask is written out"""
    filename = str(tmpdir.join('test.ecsv'))

    t = simple_table(masked=True)  # int, float, and str cols with one masked element
    t['c'][0] = ''  # This would come back as masked for default "" NULL marker

    # MaskedColumn with no masked elements. See table the MaskedColumnInfo class
    # _represent_as_dict() method for info about we test a column with no masked elements.
    t['d'] = [1, 2, 3]

    t.write(filename, serialize_method='data_mask')

    t2 = Table.read(filename)
    assert t2.masked is False
    assert t2.colnames == t.colnames
    for name in t2.colnames:
        assert np.all(t2[name].mask == t[name].mask)
        assert np.all(t2[name] == t[name])

        # Data under the mask round-trips also (unmask data to show this).
        t[name].mask = False
        t2[name].mask = False
        assert np.all(t2[name] == t[name]) 
開發者ID:holzschu,項目名稱:Carnets,代碼行數:26,代碼來源:test_ecsv.py

示例11: write

# 需要導入模塊: from astropy.io import ascii [as 別名]
# 或者: from astropy.io.ascii import write [as 別名]
def write(self, lines):
        if 'col_align' not in self.latex:
            self.latex['col_align'] = len(self.cols) * 'c'
        if 'tablealign' in self.latex:
            align = '[' + self.latex['tablealign'] + ']'
        else:
            align = ''
        if self.latex['tabletype'] is not None:
            lines.append(r'\begin{' + self.latex['tabletype'] + r'}' + align)
        add_dictval_to_list(self.latex, 'preamble', lines)
        if 'caption' in self.latex:
            lines.append(r'\caption{' + self.latex['caption'] + '}')
        lines.append(self.header_start + r'{' + self.latex['col_align'] + r'}')
        add_dictval_to_list(self.latex, 'header_start', lines)
        lines.append(self.splitter.join(self.colnames))
        units = self._get_units()
        if 'units' in self.latex:
            units.update(self.latex['units'])
        if units:
            lines.append(self.splitter.join([units.get(name, ' ') for name in self.colnames]))
        add_dictval_to_list(self.latex, 'header_end', lines) 
開發者ID:holzschu,項目名稱:Carnets,代碼行數:23,代碼來源:latex.py

示例12: generate_latex

# 需要導入模塊: from astropy.io import ascii [as 別名]
# 或者: from astropy.io.ascii import write [as 別名]
def generate_latex(self, cleaned_data):
        """
        This method takes in the data from a form.clean() and returns a string of latex.
        """

        table_data = self.create_latex_table_data(cleaned_data)

        latex_dict = ascii.latex.latexdicts['AA']
        latex_dict.update({'caption': cleaned_data.get('table_header'), 'tablefoot': cleaned_data.get('table_footer')})

        latex = io.StringIO()
        ascii.write(table_data, latex, format='latex', latexdict=latex_dict)
        return latex.getvalue() 
開發者ID:TOMToolkit,項目名稱:tom_base,代碼行數:15,代碼來源:latex.py

示例13: write_table

# 需要導入模塊: from astropy.io import ascii [as 別名]
# 或者: from astropy.io.ascii import write [as 別名]
def write_table(table, filename):
    """
    Write a table to a file.

    Parameters
    ----------
    table : Table
        Table to be written

    filename : str
        Destination for saving table.

    Returns
    -------
    None
    """
    try:
        if os.path.exists(filename):
            os.remove(filename)
        table.write(filename)
        log.info("Wrote {0}".format(filename))
    except Exception as e:
        if "Format could not be identified" not in e.message:
            raise e
        else:
            fmt = os.path.splitext(filename)[-1][1:].lower()  # extension sans '.'
            raise Exception("Cannot auto-determine format for {0}".format(fmt))
    return 
開發者ID:PaulHancock,項目名稱:Aegean,代碼行數:30,代碼來源:catalogs.py

示例14: get_all_catalogs

# 需要導入模塊: from astropy.io import ascii [as 別名]
# 或者: from astropy.io.ascii import write [as 別名]
def get_all_catalogs(xml_file, out_dir='./'):
    '''Query WISE and 2MASS catalogs and write out
    catalog files for each target in the provided APT proposal

    Parameters
    ----------
    xml_file : str
        Path to APT .xml file

    prop_id : str
        APT proposal ID number

    out_dir : str
        Output directory for catalog files

    Returns
    -------
    tuple
        Lists of shortwave and longwave catalog filenames
    '''
    target_list, target_coords = get_target_coords(xml_file)

    ensure_dir_exists(out_dir)
    #catalog_filenames_sw = get_sw_catalog(target_coords, out_dir)
    catalog_filenames = get_catalog(target_coords, out_dir)

    return target_list, target_coords, catalog_filenames 
開發者ID:spacetelescope,項目名稱:mirage,代碼行數:29,代碼來源:get_catalog.py

示例15: create_DS9_regions

# 需要導入模塊: from astropy.io import ascii [as 別名]
# 或者: from astropy.io.ascii import write [as 別名]
def create_DS9_regions(self, outputFile=None):
        ''' Writes out the bundle positions into a DS9 region file

        Parameters:
            outputFile (str):
                The output filename
        '''

        if outputFile is None:
            outputFile = 'bundlePositionsDS9.reg'

        radius = 1. / 3600.

        template = """
global color=green font="helvetica 10 normal roman" wcs=wcs
        """
        template.strip().replace('\n', ' ')

        for fibre in self.fibers:
            template += ('\nfk5;circle({0:.10f},{1:.10f},'
                         '{2:.10f}) #text = {{{3}}}').format(
                fibre[1], fibre[2], radius, int(fibre[0]))

        template += '\n'

        out = open(outputFile, 'w')
        out.write(template)
        out.close() 
開發者ID:sdss,項目名稱:marvin,代碼行數:30,代碼來源:bundle.py


注:本文中的astropy.io.ascii.write方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。