How to create a dictionary from a sentence

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Meghna J Patel
    New Member
    • Oct 2010
    • 3

    How to create a dictionary from a sentence

    given a file containing sentences separated by .,?, or !
    for example the file may contain the following: hello bob. bob goes home. how can you make the above into:
    {'hello':{'bob' :1}}
    {'bob':{'hello' :1,'goes':1,'ho me':1}}
    {'goes':{'bob': 1,'home':1}}
    for every WORD in the file you create a dictionary containing sub dictionary in which each key represents the other words found in the same sentence as the WORD and the values is the number of times the word appears in those sentences.
    because in the example above bob appears in two sentences your sub dictionary contains all the other words that appear in the same sentence and their count. this is to be done for every word in the file!
    Last edited by bvdet; Oct 31 '10, 02:02 AM. Reason: Clarify title
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Have you tried to write the code yourself? We are here to help, but we cannot write it for you. Here's an example of creating a dictionary given a sentence:

    Code:
    >>> sentence = "the only way to learn how to program in Python is to write the program yourself"
    >>> wordList = sentence.split()
    >>> dd = {}
    >>> for word in wordList:
    ... 	dd.setdefault(word, 0)
    ... 	dd[word] += 1
    ... 	
    >>> dd
    {'how': 1, 'Python': 1, 'is': 1, 'in': 1, 'yourself': 1, 'write': 1, 'to': 3, 'only': 1, 'program': 2, 'way': 1, 'learn': 1, 'the': 2}
    >>>

    Comment

    Working...