def tab_print(table_name2, status):
   print table_name2
   import glob
   tables = glob.glob('./tables/*.csv')
   table_name=table_name2.split(',')
   print table_name
   if status==False:
       for i in tables:
          if table_name[0] in i.replace('./tables/','').replace('.csv',''):
             from prettytable import from_csv
             fp = open("./tables/"+table_name[0]+".csv", "r")
             customer = from_csv(fp)
             fp.close()
             text2.delete('1.0', END) #For delete the text from input box
             #text2.insert(INSERT, '\n\n')
             text2.insert(INSERT,customer)
   elif status==True:
        cross_prod(table_name2)
        from prettytable import from_csv
        fp = open("./tables/tmp.csv", "r")
        customer = from_csv(fp)
        fp.close()
        text2.delete('1.0', END) #For delete the text from input box
         #text2.insert(INSERT, '\n\n')
        text2.insert(INSERT,customer)
示例#2
0
def makeTABLE(csvFileName):

    with open(csvFileName, 'r') as csv_file:
        print prettytable.from_csv(csv_file)
        mailContent = csv_file.readlines()

    return mailContent
def tab_print_proj(col, table_name, status):
   import glob
   tables = glob.glob('./tables/*.csv')
   if status is False:
       for i in tables:
          if table_name in i.replace('./tables/','').replace('.csv',''):
             from prettytable import from_csv
             fp = open("./tables/"+table_name+".csv", "r")
             customer = from_csv(fp)
             fp.close()
             text2.delete('1.0', END) #For delete the text from input box
             print customer.get_string(fields=col)
             text2.insert(INSERT, customer.get_string(fields=col))
   else:
       cross_prod(table_name)
       tables = glob.glob('./tables/*.csv')
       table_name=table_name.split(',')
       for i in tables:
           if table_name[0] in i.replace('./tables/','').replace('.csv','') or  table_name[1] in i.replace('./tables/','').replace('.csv',''):
               from prettytable import from_csv
               fp = open("./tables/tmp.csv", "r")
               customer = from_csv(fp)
               fp.close()
               text2.delete('1.0', END) #For delete the text from input box
               print customer.get_string(fields=col)
               text2.insert(INSERT, customer.get_string(fields=col))
def pprint_df(data_frame):
    """
    INPUT: Pandas Data Frame
    OUTPUT: A Pretty Pandas Data Frame printed to std out; returns None
    """

    output = StringIO()
    data_frame.to_csv(output)
    output.seek(0)
    print prettytable.from_csv(output)
    pass
def search_student(search='id'):
    if search == 'id':
        print('[1] Searching by ID')
        with open('student_database_final.csv', 'r') as fr:
            data_table = from_csv(fr,
                                  field_names=[
                                      'Student ID', 'Student Name', 'Age',
                                      'Gender', 'Department'
                                  ])
            print(data_table)
            choice = input('\nPlease enter your choice:\n'
                           '[1] Main Menu\n'
                           '\n'
                           'admin@sms:~$ ')

            if choice == '1':
                main.StartMain.main(self='self')
            else:
                print()
                print('[X] Wrong Input!')
                time.sleep(.50)
                if operating_system == 'Linux':
                    os.system('clear')
                elif operating_system == 'Windows':
                    os.system('cls')
                student_database()
    elif search == 'first_name':
        print('[2] Searching by First Name')
        with open('student_database_final.csv', 'r') as fr:
            data_table = from_csv(fr,
                                  field_names=[
                                      'Student ID', 'Student Name', 'Age',
                                      'Gender', 'Department'
                                  ])
            print(data_table)
            choice = input('\nPlease enter your choice:\n'
                           '[1] Main Menu\n'
                           '\n'
                           'admin@sms:~$ ')

            if choice == '1':
                main.StartMain.main(self='self')
            else:
                print()
                print('[X] Wrong Input!')
                time.sleep(.50)
                if operating_system == 'Linux':
                    os.system('clear')
                elif operating_system == 'Windows':
                    os.system('cls')
                student_database()
示例#6
0
def readCSV(csvFileName):
    with open(csvFileName, 'r') as csv_file:
        mailContent = prettytable.from_csv(csv_file)
        print mailContent, type(mailContent)
        # mailContent = ""    #csv_file.readlines()

    return mailContent
示例#7
0
    def __convertCsvToWarp(self, file):
        with open(file, 'rb') as f:
            reader = from_csv(f)

        table_converted = re.sub('\n', '<br>', str(reader))
        table_converted_with_tab = re.sub(' ', '&nbsp;', table_converted)
        return table_converted_with_tab
示例#8
0
def old():
    memo = raw_input("\nWhich record data to show : ")
    with open(memo + ".txt", "a+") as fp:
        mytable = from_csv(fp)
    os.system(clean)
    sort(mytable)
    print mytable
def mail():
    with open("running_ins.csv", "r") as fp: 
        x = from_csv(fp)
    f= open("val_table.txt","w+")
    f.write(str(x))
    f.close()
    wb = Workbook()
    ws = wb.active
    with open('running_ins.csv', 'r') as f:
        for row in csv.reader(f):
            ws.append(row)
    wb.save('all_instance_.xlsx')
    with open('running_ins.csv', 'r') as book1:
        r = csv.reader(book1, delimiter=',')
        for row in r:
            if (row[4] == 'NULL'):
                write_null_id(row[0],row[1],row[2],row[3],row[4],row[5],row[6],row[7])
                

    date=datetime.datetime.now()
    date=date.strftime("%Y-%m-%d %H:%M:%S")
    cmd = "cat running_ins.csv | column -t > /tmp/running.txt"
    os.system(cmd)
    cmd =  "mutt -s 'Running Instnace and Tags "+ date +" '  -c MAIL_ID -a /tmp/running_ins.csv < /tmp/running.txt"
    #os.system(cmd)
    cmd = "rm -rf running*"
示例#10
0
 def show_inventory_csv(self):
     """Show inventory.csv file as a table, using PrettyTable."""
     path_current_file = os.path.dirname(os.path.realpath(__file__))
     printfile = f'{path_current_file}/inventory.csv'
     with open(printfile, "r") as fp:
         x = from_csv(fp)
         print(x)
def normtable(matrix, gene_order):

    lib_order = ["Experiments", "Human Liver Carcinoma", "Heatshock", "UV", "Hepatocyte GF", "Interferons", "Brain"]
    x = 1 + np.shape(matrix)[0]
    y = 1 + np.shape(matrix)[1]
    print x, y
    a = np.arange(x*y).reshape(x,y).astype('object')

    for k in range(0, y):
        a[0,k] = lib_order[k]

    for h in range(1, x):
        a[h,0] = gene_order[h-1]

    for h in range(1, x):
        for t in range(1,7):
            a[h,t] = matrix[(h-1),(t-1)]

    with open('TPMnorm_matrix.csv', 'wb') as hello:
        writer = csv.writer(hello, delimiter=',')
        data = a
        writer.writerows(data)

    fp = open("TPMnorm_matrix.csv", "r")
    file = from_csv(fp)
    file.align="l"
    fp.close()
示例#12
0
def show_data(category, base, list):
    # creating new file to store the sorted data
    with open(".sorted_file.csv", 'w', newline='') as sortedFile:

        # writing header
        writer = csv.DictWriter(
            sortedFile,
            fieldnames=['Serial', 'Movie', 'Genres', 'Director', base])
        writer.writeheader()

        # initializing counter to track the serial
        count = 1
        for i in list:

            # checking if the genre row contains the given category or not
            if i[1].__contains__(category):
                writer.writerow({
                    'Serial': count,
                    'Movie': i[0],
                    'Genres': i[1],
                    'Director': i[2],
                    base: i[3]
                })

                # limiting the data to 20 for simplifying to user
                if count == 20:
                    break
                count = count + 1

    # displaying the data in tabular form
    x = from_csv(open('.sorted_file.csv', newline=''))
    print(x)
示例#13
0
def print_summary_from_csv() -> None:
    print(
        "----------------------------------------------------------------------"
    )
    print(
        'Summary ("KT" means "Kernel Time", "ET" means "End-to-end Time", in microseconds; "BW" means "Bandwidth" in GB/s):'
    )
    with open(csv_filename, "r") as f:
        table: PrettyTable = prettytable.from_csv(f)
        table.field_names = [
            "OP",
            "Args",
            "Lib",
            "KT(GPU)",
            "BW(GPU)",
            "KT(1 CPU)",
            "ET(1 CPU)",
            "KT(32 CPU)",
            "ET(32 CPU)",
            "Desc",
        ]
        table.del_column("Desc")
        for row in table.rows:
            row[2] = {"PyTorch": "PT", "OneFlow": "OF"}[row[2]]

        print(table)
示例#14
0
    def history(self):
        self.MSG = anal.get_all_msg(self.ACCESS_TOKEN, self.GROUP_ID)
        results = anal.get_activity(self.MSG)
        self.DF = results[0]
        self.DATA_MONTH = results[1]
        self.DATA_HOURS = results[2]
        self.DATA_DAYS = results[3]

        anal.graph(self.GROUP_ID, self.DF, self.DATA_MONTH,
                   self.DATA_HOURS, self.DATA_DAYS)

        output = StringIO()
        self.DF.to_csv(output)
        output.seek(0)
        pt = prettytable.from_csv(output)

        ret = '<pre>'
        ret += 'Analytics of GROUP# ' + str(self.GROUP_ID) + '<br>'
        ret += 'Requested at ' + datetime.datetime.today().isoformat(' ') + '<br> <br>'
        ret += 'Total Number of Messages: ' + \
            str(self.DF['Message Frequency'].sum()) + '<br>'
        ret += 'Total Number of Words: ' + str(self.DF['Words'].sum()) + '<br>'
        ret += 'Total Likes: ' + str(self.DF['Likes Received'].sum()) + '<br>'
        ret += 'Total Days: ' + str((datetime.datetime.fromtimestamp(self.MSG[0][
                                    'created_at']) - datetime.datetime.fromtimestamp(self.MSG[-1]['created_at'])).days) + '<br>'
        ret += pt.get_string() + '</pre>'
        ret += '<br> <br>'

        ret += '<img src= {{ act_url }}> <br> <br>'
        ret += '<img src={{ m_url }}>'
        ret += '<img src={{ l_url }}>'
        ret += '<img src={{ r_url }}>'

        return ret
示例#15
0
def _print_total_price(price):
    titles = [
        {'ondemand': 'on demand'},
        {'noup': '1 y no up'},
        {'1yearpartup': '1 y part up'},
        {'1yearfullup': '1 y full up'},
        {'3yearpartup': '3 y part up'},
        {'3yearfullup': '3 y full up'}
    ]
    duration = {'hrly': 1, 'mthly': 24 * 30.5, 'yrly': 24 * 30.5 * 12}


    prices = []
    for t in titles:
        prices.append(float(price[t.keys()[0]]))

    with open('prices.csv', 'w') as f:
        f.write('durat,{0}\n'.format(
            ','.join([x.values()[0] for x in titles]))
        )
        for d in sorted(duration, key=duration.get):
            f.write('{0},{1}\n'.format(
                d, ','.join([str(p * duration[d]) for p in prices])
            ))

    with open('prices.csv', 'r') as f:
        print(from_csv(f))
示例#16
0
def testFunc2(data):
    '''
    从 csv 文件中加载数据
    '''
    mycsv = open(data)
    print(mycsv.readline())
    table = from_csv(mycsv)
    mycsv.close()
    print(
        '===========================================table3-from csv=============================================='
    )

    print(table)

    print(
        '=================================table:SepalLength_Species===================================='
    )

    print(table.get_string(fields=['SepalLength', 'Species']))

    print(
        '=======================================table:60=>80 rows======================================'
    )

    print(table.get_string(start=60, end=80))
def Table(matrix, lib_order, gene_order):

    a = np.arange(250).reshape(50, 5).astype('object')

    i = 0
    a[0, 0] = 'id'

    for k in range(1, 50):
        a[k, 0] = lib_order[(k - 1)]

    for j in range(0, 4):
        i = j + 1
        a[0, i] = gene_order[j]
        for u in range(1, 50):
            a[u, i] = matrix[j, (u - 1)]

    with open('SummaryStat.csv', 'wb') as hello:
        writer = csv.writer(hello, delimiter=',')
        data = a
        writer.writerows(data)

    fp = open("SummaryStat.csv", "r")
    file = from_csv(fp)
    file.align = "l"
    fp.close()
    print(file)
示例#18
0
文件: app.py 项目: andytom/tabalisr
def process_string(csv_string):
    """Take a raw csv string and convert it into an ascii table"""
    csv_io = StringIO.StringIO(csv_string)
    table = from_csv(csv_io)

    table.align = 'l'

    return table.get_string()
示例#19
0
def pretty_print_table(dfo):
    from io import StringIO
    import prettytable
    output = StringIO()
    dfo.to_csv(output)
    output.seek(0)
    pt = prettytable.from_csv(output)
    print(pt)
def display(args):
    if (os.path.isfile(args.FILE)):
        fp = open(args.FILE, 'r')
        mytable = from_csv(fp)
        print(mytable)
        fp.close()
    else:
        print("ERROR IN FILE DISPLAY\n")
def display(args):
   if(os.path.isfile(args.FILE)):
       fp = open(args.FILE,'r')
       mytable=from_csv(fp)
       print(mytable)
       fp.close()
   else:
       print("ERROR IN FILE DISPLAY\n")
示例#22
0
def listStops():
    if not fileexists:
        print("You don't have any past searches")
        return
    f = open(fname, "r")
    tb = prettytable.from_csv(f)
    f.close()
    print(tb)
示例#23
0
def pretty_print(df):
  from StringIO import StringIO
  import prettytable    

  output = StringIO()
  df.to_csv(output, index = False, sep ='\t')
  output.seek(0)
  pt = prettytable.from_csv(output)
  print(pt)
示例#24
0
    def to_rst(cls, columns=None, sort_key=None):
        input = StringIO(cls.to_csv(columns, sort_key))
        from prettytable import from_csv
        table = from_csv(input)
        lines = table.get_string(hrules=True).splitlines()

        # Special separator between header and rows in RST
        lines[2] = lines[2].replace('-', '=')
        return '\n'.join(lines)
示例#25
0
def sale_table():  #sale list
    print()
    print('商品表')
    goods_file = open('goods.csv', 'r')
    saletb = from_csv(goods_file)
    saletb.align = 'c'
    saletb.sort = 'goods'
    print(saletb)
    goods_file.close()
示例#26
0
def main():
    """ It's script which trasnlate csv to HTML table.
    """
    with open("dataset.csv", "r") as fp:
        x = from_csv(fp) # read from csv by PT
        y = PrettyTable.get_html_string(x) # translate to html, PT
        table_html = y # store in var
        html_file=open('table.html','w') # create and write
        html_file=html_file.write(table_html) # add var html
示例#27
0
 def show_product_range_csv(self):
     """Show product_range.csv file as a table, using PrettyTable."""
     path_current_file = os.path.dirname(os.path.realpath(__file__))
     printfile = f'{path_current_file}/product_range.csv'
     with open(printfile, "r") as fp:
         x = from_csv(fp, field_names=["Product Name", "Product group",
                                       "Footprint Weight"])
         x_to_show = x[1:]
         print(x_to_show)
示例#28
0
   def dept_tables():
       #pickle.dump(dept_cnt, open('pending_departments.pkl','wb'))
       
       #pending_departments = pickle.load(open('pending_departments.pkl','rb'))
               
       print "Pending", sum(pending_departments.values())
       print "Published", sum(dept_cnt.values())
       #print set(pending_departments.items())
       #print list(set(pending_departments.items()) & set(dept_cnt.items()))
       #print [d for d in pending_departments.items()]
       
       # create a list of tuples 
       #[(key, value)]
       
       published_column = []
       for department in pending_departments:
           print ">>",department
           if dept_cnt.has_key(department):
               published_column.append(dept_cnt[department])
           else:
               published_column.append(0)
       
       print published_column 
   
       print pending_departments
       f = open('departments.csv', 'wt')
       
       writer = csv.writer(f)
      
       x=PrettyTable()
       dept_column = [item[0] for item in pending_departments.items()]
       x.add_column("Department Name", pending_departments.keys(), 'l', 't')
       x.add_column("Published",published_column,'r')
       x.add_column("Pending",pending_departments.values(),'r')
       print x  
 
       writer.writerow(['Department Name','Pending XML','Online'])
       ''' Create table to add data to  '''
      
       #print u'\u2019'.encode('utf-8') .replace(u'\u2019','') #Fix bad windows chars
       for department, count in sorted(pending_departments.items()):
           writer.writerow([department,
                    count,
                    '',
                    ])         
       
       f.close()    
       print writer
       
       fp = open('departments.csv', 'r')
       
       pt = from_csv(fp)
       pt.align['Department Name'] = "l" # Left align city names
       pt.padding_width = 1 # One space between column edges and contents (default)
       print pt
       '''
示例#29
0
    def Report(self):
        from prettytable import PrettyTable
        from prettytable import from_csv

        #table from csv
        path = "file location"
        csv_file = open(path)
        x = from_csv(csv_file)

        print(x)
示例#30
0
    def Report(self):
        from prettytable import PrettyTable
        from prettytable import from_csv

        #table from csv
        path = "/Users/Danielle/Desktop/EggIE_ver2_SOFTENG/resultegg.csv"
        csv_file = open(path)
        x = from_csv(csv_file)

        print(x)
示例#31
0
 def setUp(self):
     csv_string = """City name, Area , Population , Annual Rainfall
     Sydney, 2058 ,  4336374   ,      1214.8
     Melbourne, 1566 ,  3806092   ,       646.9
     Brisbane, 5905 ,  1857594   ,      1146.4
     Perth, 5386 ,  1554769   ,       869.4
     Adelaide, 1295 ,  1158259   ,       600.5
     Hobart, 1357 ,   205556   ,       619.5
     Darwin, 0112 ,   120900   ,      1714.7"""
     csv_fp = StringIO.StringIO(csv_string)
     self.x = from_csv(csv_fp)
示例#32
0
def stringify_pandas(pd):
    """

    :param pd: A Dataframe
    :return:
    """
    output = StringIO()
    pd.to_csv(output)

    pt = prettytable.from_csv(output)
    print(pt)
示例#33
0
def print_pandas_table(data_frame):
    '''Prints pandas dataframe to table in console'''

    from StringIO import StringIO
    import prettytable

    output = StringIO()
    data_frame.to_csv(output)
    output.seek(0)
    pt = prettytable.from_csv(output)
    print pt
示例#34
0
def top_ten(r_type, result_file):
    '''
    Print top ten test result as a table in console with specified stat data
    '''
    result = pd.read_csv(result_file, sep=",")
    print "\nTop ten in descending order " + r_type
    output = StringIO()
    result.groupby(["Template Name"]).mean().sort([r_type], ascending=False)[:10].to_csv(output, encoding='utf-8', sep=",")
    output.seek(0)
    pt = prettytable.from_csv(output)
    print pt
示例#35
0
 def setUp(self):
     csv_string = """City name, Area , Population , Annual Rainfall
     Sydney, 2058 ,  4336374   ,      1214.8
     Melbourne, 1566 ,  3806092   ,       646.9
     Brisbane, 5905 ,  1857594   ,      1146.4
     Perth, 5386 ,  1554769   ,       869.4
     Adelaide, 1295 ,  1158259   ,       600.5
     Hobart, 1357 ,   205556   ,       619.5
     Darwin, 0112 ,   120900   ,      1714.7"""
     csv_fp = StringIO.StringIO(csv_string)
     self.x = from_csv(csv_fp)
示例#36
0
文件: utils.py 项目: rahlk/Bellwether
def stringify_pandas(pd):
    """

    :param pd: A Dataframe
    :return:
    """
    output = StringIO()
    pd.to_csv(output)

    pt = prettytable.from_csv(output)
    print(pt)
 def show(self):
     if self.new: print('Belum ada Highscore')
     else:
         ranked = self.highscore_df.sort_values(by='high_score',
                                                ascending=False)
         ranked['rank'] = ranked['high_score'].rank(
             ascending=False).astype('int')
         ranked.head(10).to_csv('ranked.csv')
         with open('ranked.csv') as csv:
             table = from_csv(csv)
         print(table)
def view_students():
    print("\n")
    border_msg(" Student's Record In Our Information System ")
    try:
        fp = open(student_database, "r")
        file = from_csv(fp)
        fp.close()
        print(file)
    except (csv.Error, FileNotFoundError):
        print("\n" + smb.WARN + fontcolor.red(
            "Something Went Wrong ! Check 'students.csv' File !"))
    finally:
        continue_msg()
示例#39
0
def testFunc2(data='mycsv.csv'):
    '''
    从 csv 文件中加载数据
    '''
    mycsv = open(data)
    table = from_csv(mycsv)
    mycsv.close()
    print '===========================================table=============================================='
    print table
    print '=================================table:SepalLength_Species===================================='
    print table.get_string(fields=['SepalLength', 'Species'])
    print '=======================================table:60=>80 rows======================================'
    print table.get_string(start=60, end=80)
示例#40
0
    def executesearch(self, searchquery):
        req = urllib2.Request(url + authservice)
        creds = self.encodeUserData(u,p)
        res = urllib2.urlopen(req,creds)
        sessionxml = res.read()
        sessionkey = minidom.parseString(sessionxml).getElementsByTagName('sessionKey')[0].childNodes[0].nodeValue

        print "got session key: %s"  % sessionkey

        if not searchquery.startswith('search'):
            searchquery = 'search ' + searchquery

        req = urllib2.Request(url + searchservice)
        req.add_header('Authorization', 'Splunk %s' % sessionkey)

        search=urllib.urlencode({'search': searchquery})
        res = urllib2.urlopen(req,search)
        searchxml = res.read()
        sid = minidom.parseString(searchxml).getElementsByTagName('sid')[0].childNodes[0].nodeValue

        print "got sid:  %s" % sid

        searchservicesstatus = '/services/search/jobs/%s/' % sid
        req = urllib2.Request(url + searchservicesstatus)
        req.add_header('Authorization', 'Splunk %s' % sessionkey)

        isnotdone = True
        while isnotdone:
            res = urllib2.urlopen(req)
            searchstatus = res.read()
            isdonestatus = re.compile('isDone">(0|1)')
            isdonestatus = isdonestatus.search(searchstatus).groups()[0]
            if (isdonestatus == '1'):
                isnotdone = False

        print "got search status:  %s" % isdonestatus

        searchserviceresults = '/services/search/jobs/%s/results?output_mode=csv&count=0' % sid
        req = urllib2.Request(url + searchserviceresults)
        req.add_header('Authorization', 'Splunk %s' % sessionkey)
        res = urllib2.urlopen(req)
        searchresults = res.read()
        results = StringIO.StringIO(searchresults)
        
        table = prettytable.from_csv(results)
        
        print table
def read_print_csv(read_csv_list_criteria):
	csv_file_path_list, csv_file_name_list = find_file_path_name(test_queries_temp_dir, read_csv_list_criteria)
	if csv_file_name_list:
		from prettytable import from_csv
		for each_csv_file in csv_file_name_list:
			file_csv = open(test_queries_temp_dir + "/" + each_csv_file , "r")
			csv_table = from_csv(file_csv)
			if "all_rounds" in each_csv_file:
				print("\n\nSummary of all rounds for " + each_csv_file[:-4])
				print(csv_table.get_string(sortby=master_header))
			if "failures" in each_csv_file:
				print("\n\n Failed Queries for " + each_csv_file[:-4])
				print(csv_table.get_string(sortby=master_header))
			if "min_comparison" in each_csv_file:
				print("\n\n Fastest Execution Analysis \n")
				print(csv_table.get_string(sortby=master_header))
			file_csv.close()
def pickCut(Sequence):
    from prettytable import from_csv

    print("Which of these characterized loci is going to get lucky: ")

    fp = open("cutsites.csv", "r")
    pt = from_csv(fp)
    fp.close()

    print(pt)

    cutsiteNum = int(input("Choose your cutsite (Leftmost number):"))

    print("")
    print("You've chosen: ")
    print(pt.get_string(start = cutsiteNum-1, end = cutsiteNum))

    counter = 0
    for row in pt:
        counter += 1
        if counter == cutsiteNum:
            row.border = False
            row.header = False
            cutsite = row.get_string(fields=["sequence"]).strip()
            cutName = row.get_string(fields=["name"]).strip()
            chromosome = int(row.get_string(fields=["chromosome"]).strip())
    if chromosome >= 10:
        filename = "Scer" + str(chromosome) + ".fasta" 
    else:
        filename = "Scer0" + str(chromosome) + ".fasta"

    ChromosomeRec=SeqIO.read(filename, "fasta")
    ChromosomeSeq = ChromosomeRec.seq

    if ChromosomeSeq.find(cutsite) == -1:
        ChromosomeSeq = ChromosomeSeq.reverse_complement()

    startInd = ChromosomeSeq.find(cutsite)

    UpHomology = SeqRecord(ChromosomeSeq[startInd - 1000:startInd])
    DownHomology = SeqRecord(ChromosomeSeq[startInd + 30:startInd + 1030])
    return UpHomology, DownHomology
示例#43
0
import sys
from prettytable import from_csv

# This file uses a third party library. PrettyTable: Display data in tables using a beautiful ASCII format.
# Thank you [email protected] (code.google.com) for providing the prettytable library.

# TODO: Add filter functionality (ex. filter search engines with genre: google facebook duckduckgo -> google duckduckgo)

print "Run 'manageCollection.py' to append/remove Collection(s).\n"

collectionsData = open("Collections.csv", "r")
collectionsTable = from_csv(collectionsData)


def displayUnsorted():
  print collectionsTable
  collectionsData.close()
  x = raw_input("Press enter to exit.")
  sys.exit("Completed.")


def displaySorted():
  print "1. Sort by URL (default)"
  print "2. Sort by Genre"
  print "3. Sort by Description"
  print "4. Sort by Ranking"
  sortBy = raw_input("Select what you would like to sort by.")
  if sortBy == "1":
    print "Sorting by URL... This may take awhile."
    print collectionsTable.get_string(sortby='URL')
  elif sortBy == "2":
count["while"].append(sum_while)
with open('dict.csv', 'w', newline='') as csvfile:
           writer = csv.writer(csvfile, delimiter= ' ',quotechar='|', quoting=csv.QUOTE_MINIMAL)
           writer.writerow(["token","occurences","cycles"])
           for key,value in count.items():	       
               writer.writerow([key,value[0],value[1]])
read_fault = open("dict.csv","r")
line = read_fault.readline()
for line in read_fault:
	new_line = re.sub(r"\^M","",line)
	#print(new_line)	
	line = read_fault.readline()
read_fault.close()
reader = open("dict.csv", "r")
#reader = re.sub(r"\^M","",reader)
mytable = from_csv(reader)
print("Lookup Table Population")
print(mytable)
print("Total number of Memory Accesses is ",count["id"][0])
print("Memory Accesses")
with open('register.csv', 'w', newline='') as csvfile:
	writer = csv.writer(csvfile, delimiter= ' ',quotechar='|', quoting=csv.QUOTE_MINIMAL)
	writer.writerow(["ID","Accesses"])
	for key,value in registers_used.items():
		writer.writerow([key,value])
reader_reg = open("register.csv","r")
myreg = from_csv(reader_reg)
print(myreg)	
print("For count")
with open('for.csv', 'w', newline='') as csvfile:
	writer = csv.writer(csvfile, delimiter= ' ',quotechar='|', quoting=csv.QUOTE_MINIMAL)
示例#45
0
df.drop(['min1','min2','max1','max2'],axis=1,inplace=True)
#df = df.set_index('sample')

sampleList = df['sample'].unique()
#sampleToUse = sampleList[0]
print '#'*100
print 'Cutflow for',sampleToUse
print '#'*100
dfPrint = df.loc[df['sample']==sampleToUse]
dfPrint = dfPrint.drop(['sample','errEffRel','errEffAbs'],axis=1)
#dfPrint = dfPrint.head(10)



# print
output = StringIO()
dfPrint.to_csv(output,index=False)
output.seek(0)
pt = prettytable.from_csv(output)
print pt

print
print '#'*100
print 'latex table'
print '#'*100
print

print dfPrint.to_latex(index=False)
print
示例#46
0
文件: data.py 项目: dpych/CSV-filter
def show_csv_file(name):
    fp = open(name, "r")
    mytab = from_csv(fp)
    fp.close()
    print mytab
示例#47
0
    "__VIEWSTATEGENERATOR":"413B2934",
    "__EVENTVALIDATION":"/wEdAAgWGG2RY7jiUVmjHVLA3Vuhehn3bx2onw+gsGVGxW2uqPNH0QUya0tFKkgIABYfTinPqMgpP5oNyRNOFC9UkRd5TOB3/nlg9WQl65G7nSsW3XNGFTzwHLRD2v/eJGCd0ynBitcvyf0ePx5gnv8TklictmXUWyWAGbecBNn3zDP8oVEqyvt2y+R5rbK1ebIZhW17xDILuWgEcbUxmBSNbL8K",
    "DropDownList_CaseType":"Confirm",  #DHF Confirm
    "DropDownList_AreaType":"DIST", #DIST VILLAGE
        }

date = datetime.date(2014,12,10)
F = {}
for i in range(15):
        data["TextBox_Start"] = date
        date += datetime.timedelta(days=1)
        data['TextBox_End'] = date
        print data['TextBox_Start'] , data['TextBox_End']

        html = requests.post('http://dengue.kcg.gov.tw/KCGDengue/Mobile.aspx', verify=False, headers=headers, data=data)
        match = re.findall(u'var AREA =  new Array\((.*?)\);', html.text)
        match2 = re.findall(u'var NUMB =  new Array\((.*?)\);', html.text)
        if match == [] : continue 
        Area = [x.strip("'") for x in match[0].split(', ')]
        Count = [ int(x) for x in match2[0].split(', ')]
        final = dict(zip(Area, Count))
        F[date.strftime('%Y-%m-%d')] = final
        F.update(F)        
        
df = pd.DataFrame.from_dict(F, orient='columns')
newset = df.T.fillna(0)
output = StringIO()
newset.to_csv(output,encoding='utf-8',sep=',')
output.seek(0)
print prettytable.from_csv(output)
def display_as_table(file_name_full):
    with open(file_name_full, 'rb') as fd:
        sum_table = from_csv(fd)
        print sum_table
示例#49
0
mpl.rcParams['lines.linewidth'] = 2
mpl.rcParams['lines.markersize'] = 3
from matplotlib.widgets import Slider

import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter
import matplotlib.dates as mdates

slider_on = 1




## Open with prettytable ##
fp = open("klarup_log.csv", "rb")
table = pt.from_csv(fp)
fp.close()


d,i={},0
cols = map(list, zip(*table._rows))
for key in table.field_names:
    if cols[i].replace('.','').isdigit():
        d[key] = float(cols[i])
    else:
        d[key] = cols[i]
    i+=1
d['time_datetime'] = []
for s in d['Time']:
    d['time_datetime'].append( datetime.datetime.strptime( s , '%d. %B %Y %H:%M' ) )