By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,235 Members | 1,022 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,235 IT Pros & Developers. It's quick & easy.

How to create a dictionary from a sentence

P: 3
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:
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!
Oct 31 '10 #1
Share this Question
Share on Google+
1 Reply

Expert Mod 2.5K+
P: 2,851
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:

Expand|Select|Wrap|Line Numbers
  1. >>> sentence = "the only way to learn how to program in Python is to write the program yourself"
  2. >>> wordList = sentence.split()
  3. >>> dd = {}
  4. >>> for word in wordList:
  5. ...     dd.setdefault(word, 0)
  6. ...     dd[word] += 1
  7. ...     
  8. >>> dd
  9. {'how': 1, 'Python': 1, 'is': 1, 'in': 1, 'yourself': 1, 'write': 1, 'to': 3, 'only': 1, 'program': 2, 'way': 1, 'learn': 1, 'the': 2}
  10. >>> 
Oct 31 '10 #2

Post your reply

Sign in to post your reply or Sign up for a free account.