skip to Main Content

The following is my code:

import json


def value_list(sentence):

    word_list = sentence.split(" ")





    total_number_of_words_in_the_sentence = len(word_list)

    value_list = []

    for i in range(0, total_number_of_words_in_the_sentence):


        count1 = word_list.count(word_list[i])


        value_list.append(count1)








    return value_list


def wordlist1(sentence):
    import json

    word_list = sentence.split()







    total_number_of_words_in_the_sentence = len(word_list)

    for i in range(0,total_number_of_words_in_the_sentence):

        word_list[i] = word_list[i]


    return word_list

def word_frequency1(sentence):
    dict1 = dict(zip(wordlist1(sentence), value_list(sentence)))

    dict2 = json.dumps(dict1)

##    from collections import OrderedDict
##    my_dic = OrderedDict(dict1)
##  formatted_dict = {f'{key} : {value}' for key, value in my_dic.items()}

 ##   from collections import OrderedDict

 ##   ordered_dict = OrderedDict(formatted_dict)

##    my_list = list(my_dic)

##    json.dumps(formatted_dict)




    return dict2




print(word_frequency1("John is a businessman and John is a programmer."))

The output is:

{"John": 2, "is": 2, "a": 2, "businessman": 1, "and": 1, "programmer.": 1}

The output that I want is

{"John" : 2, "is" : 2, "a" : 2, "businessman" : 1, "and" : 1, "programmer." : 1}

How do I get this output?

I have tried a lot but not being able to get the output in this format.

Any solution guys?

i tried replace function , formatting as well as looked up some solutions online but nothing is working.

2

Answers


  1. You can use the separators argument to json.dumps to get the result you want:

    dict2 = json.dumps(dict1, separators=(', ', ' : '))
    

    Output:

    {"John" : 2, "is" : 2, "a" : 2, "businessman" : 1, "and" : 1, "programmer." : 1}
    

    Note you need to trim punctuation off your words and convert them to lowercase to get the correct result. Also, you should just use a Counter. Finally, if you don’t convert to JSON, you won’t have this issue.

    Login or Signup to reply.
  2. {
    "psid": "1345672",
    "name": "jack",
    "emailId": [email protected],
    "status": "Active",
    "accountOwner": "1345672",
    "accountType": "User",
    "appName": "sdm",
    "fapDetails": [
    {
    "role": "Initiator",
    //"isLocalDap": false,
    "dapDetails": [
    {
    "mappingRule": "indirect mapping",
    "rule": {
    "client-segment_sub_segment": {
    "client_segment": [
    "abc",
    "xyz"
    ],
    "client_sub_segment": [
    "abc",
    "xyz"
    ]
    }
    }
    },
    {
    "mappingRule": "direct mapping",
    "rule": {
    "client-segment_sub_segment": {
    "client_segment": [
    "abc",
    "xyz"
    ],
    "client_sub_segment": [
    "abc",
    "123"
    ]
    }
    }
    }
    ]
    }
    ]
    }

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search