python,data-structures,data , Converting an unknown data structure to a known data structure in Python

Converting an unknown data structure to a known data structure in Python


Tag: python,data-structures,data

I recently used an API to pull in some data from a platform I use.

But the problem is, the data that I pulled, is not a recognized data structure.

It's almost a list of dictionaries, with some extra stuff.

I need to know how can I convert it to a recognized data structure. I don't necessarily need the code to do so, just a north on what I need to study would be helpful already. I'm new to Python and I don't have a lot of coding experience.

I have a file with this data in each line, this is a sample line from the file:

[<OrderProducts at 0x24333f0, {'price_ex_tax': '99.0000', 'event_date': '', 'wrapping_name': '', 'price_tax': '0.0000', 'id': 3, 'cost_price_tax': '0.0000', 'bin_picking_number': '', 'ebay_transaction_id': '', 'wrapping_cost_ex_tax': '0.0000', 'base_total': '99.0000', 'quantity': 1, 'ebay_item_id': '', 'type': 'physical', 'product_id': 83, 'price_inc_tax': '99.0000', 'base_wrapping_cost': '0.0000', 'parent_order_product_id': None, 'option_set_id': 15, 'wrapping_message': '', 'weight': '3.0000', 'refund_amount': '0.0000', 'applied_discounts': [{'amount': 99, 'id': 'total-coupon'}], 'event_name': None, 'cost_price_ex_tax': '0.0000', 'base_price': '99.0000', 'wrapping_cost_tax': '0.0000', 'total_inc_tax': '99.0000', 'total_ex_tax': '99.0000', 'quantity_shipped': 0, 'fixed_shipping_cost': '0.0000', 'total_tax': '0.0000', 'sku': 'S-TIM-BAC-STD', 'return_id': 0, 'wrapping_cost_inc_tax': '0.0000', 'cost_price_inc_tax': '0.0000', 'name': 'University of Timbuktu Bachelor Set', 'is_bundled_product ': False, 'order_id': 614534, 'configurable_fields': [], 'order_address_id': 2, 'is_refunded': False, 'product_options': [{'display_style': 'Pick list', 'type': 'Product list', 'product_option_id': 95, 'display_value': 'Cambridge-Style Bachelor Gown, Size L', 'id': 2, 'option_id': 19, 'value': '77', 'display_name': 'Gown size', 'name': 'Bachelor gown size', 'order_product_id': 3}, {'display_style': 'Pick list', 'type': 'Product list', 'product_option_id': 97, 'display_value': 'Bachelor and Masters Trencher, Size L', 'id': 3, 'option_id': 20, 'value': '80', 'display_name': 'Trencher size', 'name': 'Trencher size', 'order_product_id': 3}], 'base_cost_price': '0.0000'}>, <OrderProducts at 0x2433420, {'price_ex_tax': '0.0000', 'event_date': '', 'wrapping_name': '', 'price_tax': '0.0000', 'id': 4, 'cost_price_tax': '0.0000', 'bin_picking_number': '', 'ebay_transaction_id': '', 'wrapping_cost_ex_tax': '0.0000', 'base_total': '0.0000', 'quantity': 1, 'ebay_item_id': '', 'type': 'physical', 'product_id': 80, 'price_inc_tax': '0.0000', 'base_wrapping_cost': '0.0000', 'parent_order_product_id': 3, 'option_set_id': None, 'wrapping_message': '', 'weight': '0.0000', 'refund_amount': '0.0000', 'applied_discounts': [], 'event_name': None, 'cost_price_ex_tax': '0.0000', 'base_price': '0.0000', 'wrapping_cost_tax': '0.0000', 'total_inc_tax': '0.0000', 'total_ex_tax': '0.0000', 'quantity_shipped': 0, 'fixed_shipping_cost': '0.0000', 'total_tax': '0.0000', 'sku': 'G-CAM-BAC-L', 'return_id': 0, 'wrapping_cost_inc_tax': '0.0000', 'cost_price_inc_tax': '0.0000', 'name': 'Cambridge-Style Bachelor Gown, Size L', 'is_bundled_product ': True, 'order_id': 614534, 'configurable_fields': [], 'order_address_id': 2, 'is_refunded': False, 'product_options': [], 'base_cost_price': '0.0000'}>, <OrderProducts at 0x2433450, {'price_ex_tax': '0.0000', 'event_date': '', 'wrapping_name': '', 'price_tax': '0.0000', 'id': 5, 'cost_price_tax': '0.0000', 'bin_picking_number': '', 'ebay_transaction_id': '', 'wrapping_cost_ex_tax': '0.0000', 'base_total': '0.0000', 'quantity': 1, 'ebay_item_id': '', 'type': 'physical', 'product_id': 87, 'price_inc_tax': '0.0000', 'base_wrapping_cost': '0.0000', 'parent_order_product_id': 3, 'option_set_id': None, 'wrapping_message': '', 'weight': '0.0000', 'refund_amount': '0.0000', 'applied_discounts': [], 'event_name': None, 'cost_price_ex_tax': '0.0000', 'base_price': '0.0000', 'wrapping_cost_tax': '0.0000', 'total_inc_tax': '0.0000', 'total_ex_tax': '0.0000', 'quantity_shipped': 0, 'fixed_shipping_cost': '0.0000', 'total_tax': '0.0000', 'sku': 'C-STD-B&M-L', 'return_id': 0, 'wrapping_cost_inc_tax': '0.0000', 'cost_price_inc_tax': '0.0000', 'name': 'Bachelor and Masters Trencher, Size L', 'is_bundled_product ': True, 'order_id': 614534, 'configurable_fields': [], 'order_address_id': 2, 'is_refunded': False, 'product_options': [], 'base_cost_price': '0.0000'}>]

EDIT: This is the code I got:

import ast
import re

order_item = re.compile("<OrderProducts at 0x[\da-f]+, ({.*?})>", re.I)

 with open('allOrderProducts2') as inf:
     for line in inf:
        order = [ast.literal_eval(op) for op in re.findall(order_item, line)]
        # ta-da! Now do something with the order
        f = open("test", "w", encoding='utf-8')
        f.write("\n".join(map(lambda x: str(x), order)))


What you have is a list ([ ... ]) containing three OrderProducts objects which, when printed, represent themselves as dictionaries ({ key1: value1, key2: value2 }).

Edit: ok, you have the string representation of three OrderProducts etc.

So the first order of business is to convert to actual Python data structures, like so:

import ast
import re

order_items = re.compile("<OrderProducts at 0x[\da-f]+, ({.*?})>", re.I).findall

with open(FILENAME) as inf:
    for line in inf:
        order = [ast.literal_eval(op) for op in order_items(line)]
        # ta-da! Now do something with the order

then continue as before:


Cleaned up a bit:

import re

DATA = "allOrderProducts2"
RESULT = "test"

order_items = re.compile("<OrderProducts at 0x[\da-f]+, ({.*?})>", re.I).findall

with open(DATA) as inf, open(RESULT, "w", "utf-8") as outf:
    # Instead of reading each line separately,
    # we can just parse the whole file in one gulp
    for item_str in order_items(
        # Also no need to convert the data
        # just to cast it back to a string again
        outf.write(item_str + "\n")

Then, when reading the RESULT file back in, you can pass each line to ast.literal_eval to turn it back into a dict.

Looking at the id and parent_order_product_id fields, it looks like what you have is a "University of Timbuktu Bachelor Set" consisting of a "Cambridge-Style Bachelor Gown, Size L" and "Bachelor and Masters Trencher, Size L" with a package price of 99.0 (units unknown) and no tax.

I wrote a quick script to figure out what a default OrderProduct looks like:

from collections import Counter
from pprint import pprint as pp

data = [
    {'price_ex_tax': '99.0000', 'event_date': '', 'wrapping_name': '', 'price_tax': '0.0000', 'id': 3, 'cost_price_tax': '0.0000', 'bin_picking_number': '', 'ebay_transaction_id': '', 'wrapping_cost_ex_tax': '0.0000', 'base_total': '99.0000', 'quantity': 1, 'ebay_item_id': '', 'type': 'physical', 'product_id': 83, 'price_inc_tax': '99.0000', 'base_wrapping_cost': '0.0000', 'parent_order_product_id': None, 'option_set_id': 15, 'wrapping_message': '', 'weight': '3.0000', 'refund_amount': '0.0000', 'applied_discounts': [{'amount': 99, 'id': 'total-coupon'}], 'event_name': None, 'cost_price_ex_tax': '0.0000', 'base_price': '99.0000', 'wrapping_cost_tax': '0.0000', 'total_inc_tax': '99.0000', 'total_ex_tax': '99.0000', 'quantity_shipped': 0, 'fixed_shipping_cost': '0.0000', 'total_tax': '0.0000', 'sku': 'S-TIM-BAC-STD', 'return_id': 0, 'wrapping_cost_inc_tax': '0.0000', 'cost_price_inc_tax': '0.0000', 'name': 'University of Timbuktu Bachelor Set', 'is_bundled_product ': False, 'order_id': 614534, 'configurable_fields': [], 'order_address_id': 2, 'is_refunded': False, 'product_options': [{'display_style': 'Pick list', 'type': 'Product list', 'product_option_id': 95, 'display_value': 'Cambridge-Style Bachelor Gown, Size L', 'id': 2, 'option_id': 19, 'value': '77', 'display_name': 'Gown size', 'name': 'Bachelor gown size', 'order_product_id': 3}, {'display_style': 'Pick list', 'type': 'Product list', 'product_option_id': 97, 'display_value': 'Bachelor and Masters Trencher, Size L', 'id': 3, 'option_id': 20, 'value': '80', 'display_name': 'Trencher size', 'name': 'Trencher size', 'order_product_id': 3}], 'base_cost_price': '0.0000'},
    {'price_ex_tax': '0.0000', 'event_date': '', 'wrapping_name': '', 'price_tax': '0.0000', 'id': 4, 'cost_price_tax': '0.0000', 'bin_picking_number': '', 'ebay_transaction_id': '', 'wrapping_cost_ex_tax': '0.0000', 'base_total': '0.0000', 'quantity': 1, 'ebay_item_id': '', 'type': 'physical', 'product_id': 80, 'price_inc_tax': '0.0000', 'base_wrapping_cost': '0.0000', 'parent_order_product_id': 3, 'option_set_id': None, 'wrapping_message': '', 'weight': '0.0000', 'refund_amount': '0.0000', 'applied_discounts': [], 'event_name': None, 'cost_price_ex_tax': '0.0000', 'base_price': '0.0000', 'wrapping_cost_tax': '0.0000', 'total_inc_tax': '0.0000', 'total_ex_tax': '0.0000', 'quantity_shipped': 0, 'fixed_shipping_cost': '0.0000', 'total_tax': '0.0000', 'sku': 'G-CAM-BAC-L', 'return_id': 0, 'wrapping_cost_inc_tax': '0.0000', 'cost_price_inc_tax': '0.0000', 'name': 'Cambridge-Style Bachelor Gown, Size L', 'is_bundled_product ': True, 'order_id': 614534, 'configurable_fields': [], 'order_address_id': 2, 'is_refunded': False, 'product_options': [], 'base_cost_price': '0.0000'}, 
    {'price_ex_tax': '0.0000', 'event_date': '', 'wrapping_name': '', 'price_tax': '0.0000', 'id': 5, 'cost_price_tax': '0.0000', 'bin_picking_number': '', 'ebay_transaction_id': '', 'wrapping_cost_ex_tax': '0.0000', 'base_total': '0.0000', 'quantity': 1, 'ebay_item_id': '', 'type': 'physical', 'product_id': 87, 'price_inc_tax': '0.0000', 'base_wrapping_cost': '0.0000', 'parent_order_product_id': 3, 'option_set_id': None, 'wrapping_message': '', 'weight': '0.0000', 'refund_amount': '0.0000', 'applied_discounts': [], 'event_name': None, 'cost_price_ex_tax': '0.0000', 'base_price': '0.0000', 'wrapping_cost_tax': '0.0000', 'total_inc_tax': '0.0000', 'total_ex_tax': '0.0000', 'quantity_shipped': 0, 'fixed_shipping_cost': '0.0000', 'total_tax': '0.0000', 'sku': 'C-STD-B&M-L', 'return_id': 0, 'wrapping_cost_inc_tax': '0.0000', 'cost_price_inc_tax': '0.0000', 'name': 'Bachelor and Masters Trencher, Size L', 'is_bundled_product ': True, 'order_id': 614534, 'configurable_fields': [], 'order_address_id': 2, 'is_refunded': False, 'product_options': [], 'base_cost_price': '0.0000'}

def get_defaults(lst_of_dct):
    defaults = {}
    majority = (len(data) + 1) // 2
    for key in lst_of_dct[0]:
            ctr = Counter(d[key] for d in lst_of_dct)
            value,count = ctr.most_common(1)[0]
            defaults[key] = value if count >= majority else ""
        except TypeError:
            # Counter doesn't like unhashable type ie lists
            defaults[key] = []
    return defaults

defaults = get_defaults(data)

which gives

{'applied_discounts': [],
 'base_cost_price': '0.0000',
 'base_price': '0.0000',
 'base_total': '0.0000',
 'base_wrapping_cost': '0.0000',
 'bin_picking_number': '',
 'configurable_fields': [],
 'cost_price_ex_tax': '0.0000',
 'cost_price_inc_tax': '0.0000',
 'cost_price_tax': '0.0000',
 'ebay_item_id': '',
 'ebay_transaction_id': '',
 'event_date': '',
 'event_name': None,
 'fixed_shipping_cost': '0.0000',
 'id': '',
 'is_bundled_product ': True,
 'is_refunded': False,
 'name': '',
 'option_set_id': None,
 'order_address_id': 2,           # should be 0
 'order_id': 614534,              # should be 0
 'parent_order_product_id': 3,    # should be 0
 'price_ex_tax': '0.0000',
 'price_inc_tax': '0.0000',
 'price_tax': '0.0000',
 'product_id': '',
 'product_options': [],
 'quantity': 1,                   # should be 0
 'quantity_shipped': 0,
 'refund_amount': '0.0000',
 'return_id': 0,
 'sku': '',
 'total_ex_tax': '0.0000',
 'total_inc_tax': '0.0000',
 'total_tax': '0.0000',
 'type': 'physical',
 'weight': '0.0000',
 'wrapping_cost_ex_tax': '0.0000',
 'wrapping_cost_inc_tax': '0.0000',
 'wrapping_cost_tax': '0.0000',
 'wrapping_message': '',
 'wrapping_name': ''}

After manually checking and fixing some bad default values,

def strip_defaults(dct, defaults):
    return {key:value for key,value in dct.items() if value != defaults[key]}

res = [strip_defaults(d, defaults) for d in data]

which removes all default-valued fields and gives us a slightly more readable version:

[{'applied_discounts': [{'amount': 99, 'id': 'total-coupon'}],
  'base_price': '99.0000',
  'base_total': '99.0000',
  'id': 3,
  'is_bundled_product ': False,
  'name': 'University of Timbuktu Bachelor Set',
  'option_set_id': 15,
  'order_address_id': 2,
  'order_id': 614534,
  'price_ex_tax': '99.0000',
  'price_inc_tax': '99.0000',
  'product_id': 83,
  'product_options': [{'display_name': 'Gown size',
                       'display_style': 'Pick list',
                       'display_value': 'Cambridge-Style Bachelor Gown, '
                                        'Size L',
                       'id': 2,
                       'name': 'Bachelor gown size',
                       'option_id': 19,
                       'order_product_id': 3,
                       'product_option_id': 95,
                       'type': 'Product list',
                       'value': '77'},
                      {'display_name': 'Trencher size',
                       'display_style': 'Pick list',
                       'display_value': 'Bachelor and Masters Trencher, '
                                        'Size L',
                       'id': 3,
                       'name': 'Trencher size',
                       'option_id': 20,
                       'order_product_id': 3,
                       'product_option_id': 97,
                       'type': 'Product list',
                       'value': '80'}],
  'quantity': 1,
  'sku': 'S-TIM-BAC-STD',
  'total_ex_tax': '99.0000',
  'total_inc_tax': '99.0000',
  'weight': '3.0000'},
 {'id': 4,
  'name': 'Cambridge-Style Bachelor Gown, Size L',
  'order_address_id': 2,
  'order_id': 614534,
  'parent_order_product_id': 3,
  'product_id': 80,
  'quantity': 1,
  'sku': 'G-CAM-BAC-L'},
 {'id': 5,
  'name': 'Bachelor and Masters Trencher, Size L',
  'order_address_id': 2,
  'order_id': 614534,
  'parent_order_product_id': 3,
  'product_id': 87,
  'quantity': 1,
  'sku': 'C-STD-B&M-L'}]


Identify that a string could be a datetime object

If I knew the format in which a string represents date-time information, then I can easily use datetime.datetime.strptime(s, fmt). However, without knowing the format of the string beforehand, would it be possible to determine whether a given string contains something that could be parsed as a datetime object with the...

Find the tf-idf score of specific words in documents using sklearn

I have code that runs basic TF-IDF vectorizer on a collection of documents, returning a sparse matrix of D X F where D is the number of documents and F is the number of terms. No problem. But how do I find the TF-IDF score of a specific term in...

Parse text from a .txt file using csv module

I have an email that comes in everyday and the format of the email is always the same except some of the data is different. I wrote a VBA Macro that exports the email to a text file. Now that it is a text file I want to parse the...

sys.argv in a windows environment

I'm attempting to learn python using the book 'a byte of python'. The code: import sys print('the command line arguments are:') for i in sys.argv: print(i) print('\n\nThe PYTHONPATH is', sys.path, '\n') outputs: the command line arguments are: C:/Users/user/PycharmProjects/helloWorld/ The PYTHONPATH is ['C:\\Users\\user\\PycharmProjects\\helloWorld', 'C:\\Users\\user\\PycharmProjects\\helloWorld', 'C:\\Python34\\', 'C:\\Python34\\DLLs', 'C:\\Python34\\lib', 'C:\\Python34', 'C:\\Python34\\lib\\site-packages']...

SQLAlchemy. 2 different relationships for 1 column

I have a simple many-to-many relationship with associated table: with following data: matches: users: users_mathces: ONE user can play MANY matches and ONE match can involve up to TWO users I want to realize proper relationships in both "Match" and "User" classes users_matches_table = Table('users_matches', Base.metadata, Column('match_id', Integer, ForeignKey('', onupdate="CASCADE",...

MySQLdb Python - Still getting error when using CREATE TABLE IF NOT EXISTS

I'm using this code to create a database with tables in Python: def CreateDatabase(): global DB_CNX global DB_NAME cursor = DB_CNX.cursor() cursor.execute("""CREATE DATABASE IF NOT EXISTS {} DEFAULT CHARACTER SET 'utf8'""".format(DB_NAME)) cursor.execute("""CREATE TABLE IF NOT EXISTS NAMES(NAME VARCHAR(50) PRIMARY KEY NOT NULL)""") DB_CNX.close() But even if I use the syntax...

How to check for multiple attributes in a list

I am making a TBRPG game using Python 2.7, and i'm currently making a quest system. I wanted to make a function that checks all of the quests in a list, in this case (quests), and tells you if any of of the quests in the list have the same...

odoo v8 - Field(s) `arch` failed against a constraint: Invalid view definition

I want to create a new view with a DB-view. When I try to install my app, DB-view was created then I get error: 2015-06-22 12:59:10,574 11988 ERROR odoo Das Feld `datum` existiert nicht Fehler Kontext: Ansicht `overview.tree.view` [view_id: 1532, xml_id: k. A., model: net.time.overview, parent_id: k. A.] 2015-06-22...

Twilio Client Python not Working in IOS Browser

I have created a simple twilio client application to make phone calls from Web Browser to phones. I used a sample Flask app to generate a secure Capability Token and used twilio.min.js library to handle calls from my HTML. The functionality works fine in Computer Browsers ans Android Phone Browsers,...

Sum of two variables in RobotFramework

I have two variables: ${calculatedTotalPrice} = 42,42 ${productPrice1} = 43,15 I executed ${calculatedTotalPrice} Evaluate ${calculatedTotalPrice}+${productPrice1} I got 42,85,15 How can I resolve it?...

Can't get value from xpath python

I want to get values from page:,Actimel-cytryna-miod-Danone.html I can get all values from first section, but I can't get values from table "Wartości odżywcze" I use this xpath: ''.join(tree2.xpath("//html/body/div[1]/div[3]/article/div[2]/div/div[4]/div[3]/div/div[1]/div[3]/table[1]/tr[3]/td[2]/span/text()")) But I'm not getting anything. With xpath like this: ''.join(tree2.xpath("//html/body/div[1]/div[3]/article/div[2]/div/div[4]/div[3]/div/div[1]/div[3]/table[1]/tr[3]/td[2]//text()")) I'm...

Python np.delete issue

A = np.array([[1,2,3],[3,4,5],[5,6,7]]) X = np.array([[0, 1, 0]]) for i in xrange(np.shape(X)[0]): for j in xrange(np.shape(X)[1]): if X[i,j] == 0.0: A = np.delete(A, (j), axis=0) I am trying to delete j from A if in X there is 0 at index j. I get IndexError: index 2 is out of...

How do variables inside python modules work?

I am coming from a Java background with Static variables, and I am trying to create a list of commonly used strings in my python application. I understand there are no static variables in python so I have written a module as follows: import os APP_NAME = 'Window Logger' APP_DATA_FOLDER_PATH...

Python: can't access newly defined environment variables

I can't access my env var: import subprocess, os print os.environ.get('PATH') # Works well print os.environ.get('BONSAI') # doesn't work But the env var is well added in my /home/me/.bashrc: BONSAI=/home/me/Utils/bonsai_v3.2 export BONSAI And I can access this env var from a new terminal....

Python: histogram/ binning data from 2 arrays.

I have two arrays of data: one is a radius values and the other is a corresponding intensity reading at that intensity: e.g. a small section of the data. First column is radius and the second is the intensities. 29.77036614 0.04464427 29.70281027 0.07771409 29.63523525 0.09424901 29.3639355 1.322793 29.29596385 2.321502 29.22783249...

Using counter on array for one value while keeping index of other values

After reading the answers on this question How to count the frequency of the elements in a list? I was wondering how to count the frequency of something, and at the same time retreive some extra information, through something like an index. For example a = ['fruit','Item#001'] b = ['fruit','Item#002']...

How to put an image on another image in python, using ImageTk?

I want to put an image in front of another one, then use this combined image as a button's background image in Tkinter. How can I do it? I am free to import Tkimage, Image. Clarify: I want to stick this on the center of this so that something like...

Calling function and passing arguments multiple times

I want to call the function multiple time and use it's returned argument everytime when it's called. For example: def myfunction(first, second, third): return (first+1,second+1,third+1) 1st call: myfunction(1,2,3) 2nd call is going to be pass returned variables: myfunction(2,3,4) and loop it until defined times. How can I do such loop?...

Strange Behavior: Floating Point Error after Appending to List

I am writing a simple function to step through a range with floating step size. To keep the output neat, I wrote a function, correct, that corrects the floating point error that is common after an arithmetic operation. That is to say: correct(0.3999999999) outputs 0.4, correct(0.1000000001) outputs 0.1, etc. Here's...

REGEX python find previous string

I'm trying to find if the last word of the string is followed by a space or a special char, and if yes return the string without this space/special char For example : "do you love dogs ?" ==> return "do you love dogs" "i love my dog " (space...

The event loop is already running

I have the following 5 files: # -*- coding: utf-8 -*- from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig)...

Pandas Dataframe Complex Calculation

I have the following dataframe,df: Year totalPubs ActualCitations 0 1994 71 191.002034 1 1995 77 2763.911781 2 1996 69 2022.374474 3 1997 78 3393.094951 I want to write code that would do the following: Citations of currentyear / Sum of totalPubs of the two previous years I want something to...

Inconsistency between gaussian_kde and density integral sum

Can one explain why after estimation of kernel density d = gaussian_kde(g[:,1]) And calculation of integral sum of it: x = np.linspace(0, g[:,1].max(), 1500) integral = np.trapz(d(x), x) I got resulting integral sum completely different to 1: print integral Out: 0.55618 ...

Python Popen - wait vs communicate vs CalledProcessError

Continuing from my previous question I see that to get the error code of a process I spawned via Popen in python I have to call either wait() or communicate() (which can be used to access the Popen stdout and stderr attributes): app7z = '/path/to/7z.exe' command = [app7z, 'a', dstFile.temp,...

group indices of list in list of lists

I am looking for an elegant solution for the following problem. I have a list of ints and I want to create a list of lists where the indices with the same value are grouped together in the order of the occurrences of said list. [2, 0, 1, 1, 3,...

Python recursive function not recursing

I'm trying to solve a puzzle, which is to reverse engineer this code, to get a list of possible passwords, and from those there should be one that 'stands out', and should work function checkPass(password) { var total = 0; var charlist = "abcdefghijklmnopqrstuvwxyz"; for (var i = 0; i...

Pandas - Dropping multiple empty columns

I have some tables where the first 11 columns are populated with data, but all columns after this are blank. I tried: df=df.dropna(axis=1,how='all') which didn't work. I then used: df = df.drop(df.columns[range(11,36)], axis=1) Which worked on the first few tables, but then some of the tables were longer or shorter...

represent an index inside a list as x,y in python

I have a list which contains 1000 integers. The 1000 integers represent 20X50 elements of dimensional array which I read from a file into the list. I need to walk through the list with an indicator in order to find close elements to each other. I want that my indicator...

Matplotlib: Plot the result of an SQL query

from sqlalchemy import create_engine import _mssql from matplotlib import pyplot as plt engine = create_engine('mssql+pymssql://**:****@') connection = engine.connect() result = connection.execute('SELECT Campaign_id, SUM(Count) AS Total_Count FROM Impressions GROUP BY Campaign_id') for row in result: print row connection.close() The above code generates an array: (54ca686d0189607081dbda85', 4174469) (551c21150189601fb08b6b64', 182) (552391ee0189601fb08b6b73', 237304) (5469f3ec0189606b1b25bcc0',...

Peewee: reducing where conditionals break after a certain length

This is what I have:, (SomeTable.stuff == entry for entry in big_list))) The problem arises when I have a relatively large list of elements in big_list and I get this: RuntimeError: maximum recursion depth exceeded Is there another way to approach this that doesn't involve splitting up the list...

Why does the update method in Tkinter cause the window to freeze?

First of all, I know Tkinter isn't thread safe and this problem has something to do with that but I wanted to find out formally why this code makes a window that displays but is unresponsive. from Tkinter import * root = Tk() c = Canvas() c.pack() c.create_line(10,10, 30, 30)...

Inserting a variable in MongoDB specifying _id field

I want to insert a variable, say, a = {1:2,3:4} into my database with a particular id "56". It is very clear from the docs that I can do the following: db.testcol.insert({"_id": "56", 1:2, 3:4}) However, I cannot figure out any way to insert "a" itself, specifying an id. In...

Python - Opening and changing large text files

I have a ~600MB Roblox type .mesh file, which reads like a text file in any text editor. I have the following code below: mesh = open("file.mesh", "r").read() mesh = mesh.replace("[", "{").replace("]", "}").replace("}{", "},{") mesh = "{"+mesh+"}" f = open("p2t.txt", "w") f.write(mesh) It returns: Traceback (most recent call last): File...

Sort when values are None or empty strings python

I have a list with dictionaries in which I sort them on different values. I'm doing it with these lines of code: def orderBy(self, col, dir, objlist): if dir == 'asc': sorted_objects = sorted(objlist, key=lambda k: k[col]) else: sorted_objects = sorted(objlist, key=lambda k: k[col], reverse=True) return sorted_objects Now the problem...

Displaying a 32-bit image with NaN values (ImageJ)

I wrote a multilanguage 3-D image denoising ImageJ plugin that does some operations on an image and returns the denoised image as a 1-D array. The 1-D array contains NaN values (around the edges). The 1-D array is converted back into an image stack and displayed. It is simply black....

How do I read this list and parse it?

I'm using requests and the output I get from the sites API is a list, I've been stuck trying to parse it to get the data from it. I use r = requests.get(urlas, params=params) r.json() to get the data I want. Here is a snippet of the list [{'relation_type': None,...

Replace nodejs for python?

i'm working in a HTML5 multiplayer game, and i need a server to sync player's movement, chat, battles, etc. So I'm looking for ways to use python instead nodejs, because i have I have more familiarity with python. The server is simple: var express = require('express'); var app = express();...

ctypes error AttributeError symbol not found, OS X 10.7.5

I have a simple test function on C++: #include <stdio.h> #include <string.h> #include <stdlib.h> #include <locale.h> #include <wchar.h> char fun() { printf( "%i", 12 ); return 'y'; } compiling: gcc -o -shared -fPIC test.cpp and using it in python with ctypes: from ctypes import cdll from ctypes import c_char_p...

Spring-integration scripting with Python

I'm trying to use Python with spring-integration and jython-standalone-2.7.0: Here is my application context: <int:inbound-channel-adapter id="in" channel="exampleChannel" > <int:poller fixed-rate="1000" /> <int-script:script lang="python" location="script/" /> </int:inbound-channel-adapter> <int:channel id="exampleChannel" /> <int-ip:udp-outbound-channel-adapter id="udpOut" channel="exampleChannel" host="" port="11111" /> Here is my script in Python: print "Python"...

How does the class_weight parameter in scikit-learn work?

I am having a lot of trouble understanding how the class_weight parameter in scikit-learn's Logistic Regression operates. The Situation I want to use logistic regression to do binary classification on a very unbalanced data set. The classes are labelled 0 (negative) and 1 (positive) and the observed data is in...

Django: html without CSS and the right text

First of all, this website that I'm trying to build is my first, so take it easy. Thanks. Anyway, I have my home page, home.html, that extends from base.html, and joke.html, that also extends base.html. The home page works just fine, but not the joke page. Here are some parts...

SyntaxError: invalid syntax?

Good afternoon, I am developing a script in python and while I am trying to compile it from the terminator/terminal i always get this error, but I cannot understand where is the syntax error? File "", line 128 print ('########################') ^ SyntaxError: invalid syntax Then I just change the position...

trying to understand LSH through the sample python code

the concise python code i study for is here Question A @ line 8 i do not really understand the syntax meaning for "res = res << 1" for the purpose of "get_signature" Question B @ line 49 (SOLVED BY myself through another Q&A) "xor = r1^r2" does not really...

In sklearn, does a fitted pipeline reapply every transform?

Apologies if this is obvious but I couldn't find a clear answer to this: Say I've used a pretty typical pipeline: feat_sel = RandomizedLogisticRegression() clf = RandomForestClassifier() pl = Pipeline([ ('preprocessing', preprocessing.StandardScaler()), ('feature_selection', feat_sel), ('classification', clf)]),y) Now when I apply pl on a new set, pl.predict(X_classify); is RandomizedLogisticRegression going...

how to enable a entry by clicking a button in Tkinter?

I need to activate many entries when button is clicked please do not write class based code, modify this code only because i need to change the whole code for the project as i did my whole project without classes from Tkinter import * import ttk x='disabled' def rakhi(): global...

Count function counting only last line of my list

Count function counting only last line of my list N = int(raw_input()) cnt = [] for i in range(N): string = raw_input() for j in range(1,len(string)): if string[j] =='K': cnt.append('R') elif string[j] =='R': cnt.append('R') if string[0] == 'k': cnt.append('k') elif string[0] == 'R': cnt.append('R') print cnt.count('R') if I am giving...

How to remove structure with python from this case?
How to remove "table" from HTML using python? I had case like this: paragraph = ''' <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quidem molestiae consequuntur officiis corporis sint.<br /><br /> <table> <tr> <td> text title </td> <td> text title 2 </td> </tr> </table> <p> lorem ipsum</p> ''' how...

How to use template within Django template?

I have the django template like below: <a href="{{ }}" target="_blank"><h1 class="title">{{ mylist.0.title }}</h1></a> <p> {{ mylist.0.text|truncatewords:50 }}<br> ... (the actual template is quite big) It should be used 10 times on the same page, but 'external' html elements are different: <div class="row"> <div class="col-md-12 col-lg-12 block block-color-1"> *django...

Create an exe with Python 3.4 using cx_Freeze

I have found two other articles about this problem on Stack Exchange but none of them has a clear answer: is it possible to create a .exe of a Python 3.4 script? The only solution I found was to use cx_Freeze. I used it, and it indeed created an executable...

How to change the IP address of Amazon EC2 instance using boto library

How can I assign a new IP address (or Elastic IP) to an already existing AWS EC2 instance using boto library.