简体   繁体   中英

Store words of file in dictionary

I want to store the words of a text file in a dictionary.

My code is

   word=0
   char=0
   i=0
   a=0
   d={}
   with open("m.txt","r") as f:
      for line in f:
          w=line.split()
          d[i]=w[a]
          i=i+1
          a=a+1
          word=word+len(w)
          char=char+len(line)
          print(word,char)
  print(d)  

my text file is

 jdfjdnv  dj g gjv,kjvbm

but the problem is that the dictionary is storing only the first word of the text file .how to store the rest of the words.please help

How many lines does your text file have? If it only has one line your loop executes only once, splits whole line into separate words, then saves one word in Python dict. If you want to save all words from this text file with one line you need to add another loop. Like this:

for word in line.split():
    d[i] = word
    i += 1

You only store the first word because you only have one line in the file, and your only for loop is over the lines.

Generally, if you are going to key the dictionary by index, you can just use the list you are already making:

   w = []
   char = 0
   with open("m.txt", "r") as f:
       for line in f:
           char += len(line)
           w.extend(line.split())
   word = sum(map(len, w))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM