【问题标题】:How to create a dictionary for a text file如何为文本文件创建字典
【发布时间】:2015-03-27 12:57:41
【问题描述】:

我的程序打开一个文件,它可以计算其中包含的单词,但我想创建一个包含文本中所有唯一单词的字典 例如,如果“计算机”一词出现 3 次,我希望将其计为一个唯一词

def main():

    file = input('Enter the name of the input file: ')
    infile = open(file, 'r')

    file_contents = infile.read()

    infile.close()

    words = file_contents.split()

    number_of_words = len(words)

    print("There are", number_of_words, "words contained in this paragarph")

main()

【问题讨论】:

    标签: python dictionary


    【解决方案1】:

    使用一组。这将只包括独特的词:

    words = set(words)
    

    如果你不关心大小写,你可以这样做:

    words = set(word.lower() for word in words)
    

    这假设没有标点符号。如果有,您需要去掉标点符号。

    import string
    words = set(word.lower().strip(string.punctuation) for word in words)
    

    如果您需要跟踪每个单词的数量,只需将上面示例中的 set 替换为 Counter

    import string
    from collections import Counter
    words = Counter(word.lower().strip(string.punctuation) for word in words)
    

    这会给你一个类似字典的对象,告诉你每个单词有多少。

    您还可以从中获取唯一单词的数量(尽管如果您只关心它会更慢):

    import string
    from collections import Counter
    words = Counter(word.lower().strip(string.punctuation) for word in words)
    nword = len(words)   
    

    【讨论】:

      【解决方案2】:

      @TheBlackCat 他的解决方案有效,但只为您提供字符串/文件中有多少唯一词。此解决方案还显示它发生了多少次。

      dictionaryName = {}
      for word in words:
          if word not in list(dictionaryName):
              dictionaryName[word] = 1
          else:
              number = dictionaryName.get(word)
              dictionaryName[word] = dictionaryName.get(word) + 1
      print dictionaryName
      

      测试:

      words = "Foo", "Bar", "Baz", "Baz"
      output: {'Foo': 1, 'Bar': 1, 'Baz': 2}
      

      【讨论】:

      • 1. dictionaryName 作为变量的名称违反了 PEP-0008。 2. 不需要if word not in list(dictionaryName),因为你可以直接通过字典键获取值,如果键不存在则可以通过默认值获取。
      【解决方案3】:

      可能更清洁和快速的解决方案:

      words_dict = {}
      for word in words:
          word_count = words_dict.get(word, 0)
          words_dict[word] = word_count + 1
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-04-10
        • 1970-01-01
        • 2020-03-14
        • 1970-01-01
        • 2012-07-16
        • 2012-03-08
        相关资源
        最近更新 更多