This is my program where when sending an input string of text, the response is each word and how many times it occurs (returned as JSON objects):
from swagger_server.models.result import Result # noqa: E501
def get_concordance(body): # noqa: E501
"""Calculate
Post text to generate concordance # noqa: E501
:param body: Text to be analyzed
:type body: dict | bytes
:rtype: Result
"""
input_text = body.decode('utf-8')
split_string = (input_text.split())
def word_count():
# counts = dict()
counts = {}
for word in split_string:
if word in counts:
counts[word] += 1
else:
counts[word] = 1
return counts
try:
response = {
"concordance": [
{
"count": word_count(),
"token": split_string
}
],
"input": input_text
}
except Exception as error:
response = {
"error": repr(error)
}
return response
Right now the JSON output looks like:
{
"concordance": [
{
"count": {
"The": 1,
"brown": 2,
"fox": 1,
"jumped": 1,
"log.": 1,
"over": 1,
"the": 1
},
"token": [
"The",
"brown",
"fox",
"jumped",
"over",
"the",
"brown",
"log."
]
}
],
"input": "The brown fox jumped over the brown log."
}
However, I am trying to have the output formatted to look like:
{
"concordance": [
{
"token": "brown",
"count": 2
},
{
"token": "fox",
"count": 1
},
{
"token": "jumped",
"count": 1
},
{
"token": "log",
"count": 1
},
{
"token": "over",
"count": 1
},
{
"token": "the",
"count": 1
}
],
"input": "The brown fox jumped over the brown log."
}
Does anyone know how I can change my code so that it prints it correctly? I am not sure how I can separate each word in the list and associate it with its count. Thank you.
The brown fox jumped over the brown log.