简体   繁体   English

将文件中的单词存储在字典中

[英]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. 如果只有一行,则循环仅执行一次,将整行拆分为单独的单词,然后在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. 您只存储第一个单词,因为文件中只有一行,并且您的for循环在这些行上。

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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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