Categories
Python Answers

How to generate set partitions in Python?

Sometimes, we want to generate set partitions in Python.

In this article, we’ll look at how to generate set partitions in Python.

How to generate set partitions in Python?

To generate set partitions in Python, we can use the more_itertools module.

For instance, we write:

pip install more-itertools

Then we write:

import more_itertools as mit

lst = [1, 2, 3]
partitions = [
    part for k in range(1,
                        len(lst) + 1) for part in mit.set_partitions(lst, k)
]
print(partitions)

We use list comprehension with mit.set_partitions(lst, k) to create partitions by dividing it with k as the boundary.

It returns the part list which has the partition with k as the boundary.

And we return a nested list with all the partitions with different values of k from 1 to len(lst).

Therefore, partitions is [[[1, 2, 3]], [[1], [2, 3]], [[1, 2], [3]], [[2], [1, 3]], [[1], [2], [3]]].

Conclusion

To generate set partitions in Python, we can use the more_itertools module.

Categories
Python Answers

How to replace non-ASCII characters with a single space in Python?

Sometimes, we want to replace non-ASCII characters with a single space in Python.

In this article, we’ll look at how to replace non-ASCII characters with a single space in Python.

How to replace non-ASCII characters with a single space in Python?

To replace non-ASCII characters with a single space in Python, we can use the unidecode module.

To install it, we run:

pip install unidecode

Then we use it by writing:

from unidecode import unidecode


def remove_non_ascii(text):
    return unidecode(text)


n = remove_non_ascii(u"Ceñía")
print(n)

We have the remove_non_ascii function that takes the text string.

Then we call unideocde with text to return an ASCII string.

Next, we call remove_non_ascii function with the u"Ceñía" unicode string.

Therefore, n is 'Cenia'.

Conclusion

To replace non-ASCII characters with a single space in Python, we can use the unidecode module.

Categories
Python Answers

How to get string objects instead of Unicode from JSON with Python?

Sometimes, we want to get string objects instead of Unicode from JSON with Python.

In this article, we’ll look at how to get string objects instead of Unicode from JSON with Python.

How to get string objects instead of Unicode from JSON with Python?

To get string objects instead of Unicode from JSON with Python, we can use PyYAML to parse the JSON instead of the json module.

This is because JSON is a subset of YAML.

To install it, we run:

pip install PyYAML

Then we can call the safe_load method to parse a JSON string into string objects:

import json
import yaml

list_org = ['a', 'b']
list_dump = json.dumps(list_org)
a = yaml.safe_load(list_dump)
print(a)

We convert the list_org list to JSON with json.dumps.

Then we call yaml.safe_load on list_dump to return list parsed from the list_dump JSON string.

Therefore, a is:

['a', 'b']

and both strings are regular strings.

Conclusion

To get string objects instead of Unicode from JSON with Python, we can use PyYAML to parse the JSON instead of the json module.

This is because JSON is a subset of YAML.

Categories
Python Answers

How to convert a PIL Image into a NumPy array with Python?

Sometimes, we want to convert a PIL Image into a NumPy array with Python.

In this article, we’ll look at how to convert a PIL Image into a NumPy array with Python.

How to convert a PIL Image into a NumPy array with Python?

To convert a PIL Image into a NumPy array with Python, we call the Image.open method from PIL.

Next, we call convert with 'L' to convert that to an image object that we can pass into numpy.array.

Then we call numpy.array with the returned image object to return a NumPy array.

For instance, we write:

import numpy
from PIL import Image

img = Image.open("art.png").convert("L")
imgarr = numpy.array(img)
print(imgarr)

to call Image.open with the path to the image file.

Then we call convert with 'L' to return image object that we pass into numpy.array to generate the array and return it,

Therefore, imgarr is something like:

[[29 29 29 ... 29 29 29]
 [29 29 29 ... 29 29 29]
 [29 29 29 ... 29 29 29]
 ...
 [29 29 29 ... 29 29 29]
 [29 29 29 ... 29 29 29]
 [29 29 29 ... 29 29 29]]

Conclusion

To convert a PIL Image into a NumPy array with Python, we call the Image.open method from PIL.

Next, we call convert with 'L' to convert that to an image object that we can pass into numpy.array.

Then we call numpy.array with the returned image object to return a NumPy array.

Categories
Python Answers

How to fix the ‘NumPy array is not JSON serializable’ issue with Python?

Sometimes, we want to fix the ‘NumPy array is not JSON serializable’ issue with Python.

In this article, we’ll look at how to fix the ‘NumPy array is not JSON serializable’ issue with Python.

How to fix the ‘NumPy array is not JSON serializable’ issue with Python?

To fix the ‘NumPy array is not JSON serializable’ issue with Python, we can use the json.dump method with the codecs.open method and the NumPy array’s tolist method.

For instance, we write:

import numpy as np
import codecs, json

a = np.arange(10).reshape(2, 5)
b = a.tolist()
file_path = "data.json"
json.dump(b,
          codecs.open(file_path, 'w', encoding='utf-8'),
          separators=(',', ':'),
          sort_keys=True,
          indent=2)

We create an array with numbers 0 to 9 with np.arange(10).

And we convert that to a 2×5 array with reshape(2, 5).

Next, we call a.tolist to convert the a NumPy array to a list.

Then we call json.dump with b, the file to write to, the separators to insert between entries, whether to sort keys, and the number of spaces to indent to generate the JSON file from the b list.

codecs.open opens the data.json for writing.

And so data.json has:

[
  [
    0,
    1,
    2,
    3,
    4
  ],
  [
    5,
    6,
    7,
    8,
    9
  ]
]

Conclusion

To fix the ‘NumPy array is not JSON serializable’ issue with Python, we can use the json.dump method with the codecs.open method and the NumPy array’s tolist method.