【问题标题】:how can I read from a file and append each word to a dictionary?如何从文件中读取并将每个单词附加到字典中?
【发布时间】:2013-02-04 03:52:50
【问题描述】:

我想要做的是从文件中读取,然后对于每个单词,将其连同其出现次数一起附加到字典中。

示例:

'今天是星期天。明天不是星期天。'

我的字典会是这样的: {'今天':1,'是':2,'星期日':2,'明天':1,'不':1}

我的方法是使用 readline 和 split 创建一个列表,然后将每个元素及其值附加到一个空字典中,但到目前为止它并没有真正起作用。这是我到目前为止所拥有的,虽然它不完整:

file = open('any_file,txt', 'r')

for line in file.readline().split():
     for i in range(len(line)):
         new_dict[i] = line.count(i)  # I'm getting an error here as well, saying that  
return new_dict                       # I can't convert int to str implicitly 

这样做的问题是,当我的字典在读取每一行时更新时,单词的值不会累积。因此,如果在另一行 'sunday' 出现 3 次,我的字典将包含 {'sunday': 3} 而不是 {'sunday': 5}。有什么帮助吗?我不知道从这里去哪里,而且我对这一切都很陌生。

【问题讨论】:

  • 另一个问题是,如果“sunday”在一行中出现 3 次,你就在做 line.count("sunday") 3 次,这是浪费

标签: python file dictionary


【解决方案1】:

您正在寻找collections.Counter

例如:

from itertools import chain

with open("file.txt") as file:
    Counter(chain.from_iterable(line.split() for line in file))

(也使用itertools.chain.from_iterable() generator expression。)

请注意,您的示例仅适用于第一行,我认为这不是故意的,并且此解决方案适用于整个文件(显然交换它很简单)。

【讨论】:

    【解决方案2】:

    这是一个不处理标点符号的简单版本

    from collections import Counter
    counter = Counter()
    with open('any_file,txt', 'r') as file:
        for line in file:
            for word in line.split():
                counter[word] += 1
    

    也可以这样写:

    from collections import Counter
    counter = Counter(word for line in file for word in line.split())
    

    这是使用dict 解决问题的一种方法

    counter = {}
    with open('any_file,txt', 'r') as file:
        for line in file:
            for word in line.split():
                if word not in counter:
                    counter[word] = 1
                else:
                    counter[word] += 1
    

    【讨论】:

    • 这种方式违背了使用collections.Counter() 的意义。 (编辑:使用编辑会好一些,尽管它是扁平化迭代的一种低效方式)。
    • 收集计数器是唯一的方法吗?我假设任何其他解决方案都只是冗长而乏味
    • @peppy 当然这不是唯一的解决方案,但它很高效,工作已经为您完成。
    • @peppy,你可以用dict 来做,如果它不存在,你只需要添加键,然后将值加 1
    • @Peppy。我使用字典添加了一个版本。还有其他方法,但我认为这个方法很容易理解。
    【解决方案3】:

    试试这个

     file = open('any_file.txt', 'r')
     myDict = {}
     for line in file:
         lineSplit = line.split(" ")
         for x in xrange(len(lineSplit)):
             if lineSplit[x] in myDict.keys(): myDict[lineSplit[x]] += 1
             else: myDict[lineSplit[x]] = 1
    
     file.close()
    
     print myDict
    

    【讨论】:

      【解决方案4】:

      您使用 Python 3 还是 Python 2.7?

      如果是,请使用集合库中的计数器:

      import re
      from collections import Counter
      words = re.findall('\w+', open('any_file.txt').read().lower())
      Counter(words).most_common(10)
      

      但是你得到了元组列表。将元组列表转换为字典应该很容易。

      【讨论】:

      • 这个正则表达式并不是真正需要的,collections 存在于 2.x 中。
      • @Lattyware,对不起,我应该让自己更清楚。计数器在 python 2 中不可用。
      • 我刚测试过,至少2.7肯定有。
      • @Lattyware,对不起,我才意识到我使用的是 python 2.6。计数器是在 python 2.7 中引入的。 docs.python.org/2/library/collections.html
      猜你喜欢
      • 1970-01-01
      • 2013-12-05
      • 2023-03-02
      • 1970-01-01
      • 2013-09-14
      • 1970-01-01
      • 2016-02-12
      • 2013-11-15
      • 1970-01-01
      相关资源
      最近更新 更多