How to get count dict of items but maintain the order in which they appear?

You can use the recipe that uses collections.Counter and collections.OrderedDict: from collections import Counter, OrderedDict class OrderedCounter(Counter, OrderedDict): ‘Counter that remembers the order elements are first encountered’ def __repr__(self): return ‘%s(%r)’ % (self.__class__.__name__, OrderedDict(self)) def __reduce__(self): return self.__class__, (OrderedDict(self),) words = [“oranges”, “apples”, “apples”, “bananas”, “kiwis”, “kiwis”, “apples”] c = OrderedCounter(words) print(c) # OrderedCounter(OrderedDict([(‘oranges’, 1), … Read more

How to search and replace with a counter-based expression in Vim?

It is possible to have a counter using the substitute-with-an-expression feature (see :help sub-replace-\=). Unfortunately, since the \= construct allows only expressions, the :let command cannot be used, and therefore, a variable cannot not be set the usual way. However, there is a simple trick to change the value of a variable in expression if that variable … Read more

Creating an Ordered Counter

OrderedCounter is given as an example in the OrderedDict documentation, and works without needing to override any methods: class OrderedCounter(Counter, OrderedDict): pass When a class method is called, Python has to find the correct method to execute. There is a defined order in which it searches the class hierarchy called the “method resolution order” or … Read more

How to count the number of words in a sentence, ignoring numbers, punctuation and whitespace?

str.split() without any arguments splits on runs of whitespace characters: >>> s=”I am having a very nice day.” >>> >>> len(s.split()) 7 From the linked documentation: If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain … Read more