Categories
Python Answers

How to parse data in JSON format with Python?

Sometimes, we want to parse data in JSON format with Python.

In this article, we’ll look at how to parse data in JSON format with Python.

How to parse data in JSON format with Python?

To parse data in JSON format with Python, we can use the json.loads method.

For instance, we write:

import json

data = json.loads('{"one" : "1", "two" : "2", "three" : "3"}')
print(data['two'])

We import the json module and call the json.loads method with a JSON string.

It returns a dictionary with the keys being the JSON object’s keys and the values being the JSON object’s values and we assign that to data.

Therefore, we see 2 printed.

Conclusion

To parse data in JSON format with Python, we can use the json.loads method.

Categories
Python Answers

How to select items randomly but weighted by probability with Python?

Sometimes, we want to select items randomly but weighted by probability with Python.

In this article, we’ll look at how to select items randomly but weighted by probability with Python.

How to select items randomly but weighted by probability with Python?

To select items randomly but weighted by probability with Python, we can call random.choice with the weights parameter set to the probability of each item being chosen.

For instance, we write:

import random

choices = random.choices(
  population=[['a','b'], ['b','a'], ['c','b']],
  weights=[0.2, 0.2, 0.6],
  k=10
)

print(choices)

We call random.choices with population set to the items that can be chosen.

weights has the probability of each item in population being chosen.

k is the number items to choose.

The items chosen are returned in a list and assigned to choices.

Therefore, choices is:

[['a', 'b'], ['c', 'b'], ['a', 'b'], ['c', 'b'], ['c', 'b'], ['c', 'b'], ['b', 'a'], ['a', 'b'], ['c', 'b'], ['a', 'b']]

Conclusion

To select items randomly but weighted by probably with Python, we can call random.choice with the weights parameter set to the probability of each item being chosen.

Categories
Python Answers

How to replace multiple substrings of a string in Python?

Sometimes, we want to replace multiple substrings of a string in Python.

In this article, we’ll look at how to replace multiple substrings of a string in Python.

How to replace multiple substrings of a string in Python?

To replace multiple substrings of a string in Python, we can use the Python string’s `replace method.

For instance, we write:

def replace_all(text, dic):
    for i, j in dic.items():
        text = text.replace(i, j)
    return text

d = { "cat": "dog", "dog": "pig"}
my_sentence = "This is my cat and this is my dog."
new_sentence = replace_all(my_sentence, d)
print(new_sentence)    

to create the replace_all function.

We loop through the dic dictionary’s key-value pairs which are returned by dic.items.

Then we call text.replace with i and j, which is the original substring and the replacement substring respectively.

And we assign the new returned string to text.

Finally, we return text which has all the replacements done.

Next, we call replace_all with my_sentence and d.

And new_sentence is 'This is my pig and this is my pig.'.

Conclusion

To replace multiple substrings of a string in Python, we can use the Python string’s `replace method.

Categories
Python Answers

How to read streaming input from Python subprocess.communicate()?

Sometimes, we want to read streaming input from Python subprocess.communicate() method.

In this article, we’ll look at how to read streaming input from Python subprocess.communicate() method.

How to read streaming input from Python subprocess.communicate()?

To read streaming input from Python subprocess.communicate() method, we can use the subprocess.Popen method.

For instance, we write:

from subprocess import Popen, PIPE

with Popen(["ls", "-l"], stdout=PIPE, bufsize=1,
           universal_newlines=True) as p:
    for line in p.stdout:
        print(line, end='')

We call Popen with the command and argument in the list.

And we set stdout to PIPE to pipe the output to p.stdout.

Then we loop through each line in p.stdout and print them with print.

Conclusion

To read streaming input from Python subprocess.communicate() method, we can use the subprocess.Popen method.

Categories
Python Answers

How to remove accents (normalize) in a Python unicode string?

Sometimes, we want to remove accents (normalize) in a Python unicode string.

In this article, we’ll look at how to remove accents (normalize) in a Python unicode string.

How to remove accents (normalize) in a Python unicode string?

To remove accents (normalize) in a Python unicode string, we can use the unicodedata.normalize method.

For instance, we write:

import unicodedata


def strip_accents(s):
    return ''.join(c for c in unicodedata.normalize('NFD', s)
                   if unicodedata.category(c) != 'Mn')
no_accent = strip_accents(u"A \u00c0 \u0394 \u038E")      
print(no_accent)             

We call unicodedata.normalize on the s string and then join all the returned letters in the list with join.

We filter out all the non-spacing characters in s with if unicodedata.category(c) != 'Mn'

Therefore, no_accent is 'A A Δ Υ'.

Conclusion

To remove accents (normalize) in a Python unicode string, we can use the unicodedata.normalize method.