【问题标题】:How to add words from a text file to a dictionary depending on the name?如何根据名称将文本文件中的单词添加到字典中?
【发布时间】:2012-10-11 19:10:40
【问题描述】:

所以我有一个文本文件,其中包含罗密欧与朱丽叶戏剧第 1 幕的剧本,我想计算某人说出一个词的次数。

这是正文:http://pastebin.com/X0gaxAPK

文本中有 3 个人在讲话:Gregory、Sampson 和 Abraham。

基本上,我想为三位演讲者中的每一个制作 3 个不同的词典(如果这是最好的方法吗?)。用人们分别说的单词填充字典,然后计算他们在整个脚本中说出每个单词的次数。

我该怎么做呢?我想我可以算出字数,但是对于如何区分谁说什么并将其放入每个人的 3 个不同的字典中,我有点困惑。

我的输出应该是这样的(这不正确,只是一个例子):

Gregory - 
25: the
15: a
5: from
3: while
1: hello
etc

其中数字是该词在文件中出现的频率。

现在我已经编写了读取文本文件、去除标点符号并将文本编译成列表的代码。我也不想使用任何外部模块,我想用老式的方式来学习,谢谢。

您不必发布确切的代码,只需解释我需要做什么,希望我能弄清楚。我正在使用 Python 3。

【问题讨论】:

  • 您可能想要使用字典,其中键是名称,值是您所描述的字典

标签: python file list dictionary


【解决方案1】:
import collections
import string
c = collections.defaultdict(collections.Counter)
speaker = None

with open('/tmp/spam.txt') as f:
  for line in f:
    if not line.strip():
      # we're on an empty line, the last guy has finished blabbing
      speaker = None
      continue
    if line.count(' ') == 0 and line.strip().endswith(':'):
      # a new guy is talking now, you might want to refine this event
      speaker = line.strip()[:-1]
      continue
    c[speaker].update(x.strip(string.punctuation).lower() for x in line.split())

示例输出:

In [1]: run /tmp/spam.py

In [2]: c.keys()
Out[2]: [None, 'Abraham', 'Gregory', 'Sampson']

In [3]: c['Gregory'].most_common(10)
Out[3]: 
[('the', 7),
 ('thou', 6),
 ('to', 6),
 ('of', 4),
 ('and', 4),
 ('art', 3),
 ('is', 3),
 ('it', 3),
 ('no', 3),
 ('i', 3)]

【讨论】:

    【解决方案2】:

    你不想马上去掉标点符号。新行前面的冒号告诉您一个人的报价从哪里开始和结束。这很重要,因此您知道将给定引号中的单词附加到哪个字典。您可能需要某种 if-else 附加到不同的字典,具体取决于当前说话的人。

    【讨论】:

      【解决方案3】:

      这是一个简单的实现:

      from collections import defaultdict
      
      import nltk
      
      def is_dialogue(line):
          # Add more rules to check if the 
          # line is a dialogue or not
          if len(line) > 0 and line.find('[') == -1 and line.find(']') == -1:
              return True
      
      def get_dialogues(filename, people_list):
          dialogues = defaultdict(list)
          people_list = map(lambda x: x+':', people_list)
          current_person = None
          with open(filename) as fin:
              for line in fin:
                  current_line = line.strip().replace('\n','')
                  if  current_line in people_list:
                      current_person = current_line
                  if (current_person is not None) and (current_line != current_person) and is_dialogue(current_line):
                      dialogues[current_person].append(current_line)
          return dialogues
      
      def get_word_counts(dialogues):
          word_counts = defaultdict(dict)
          for (person, dialogue_list) in dialogues.items():
              word_count = defaultdict(int)
              for dialogue in dialogue_list:
                  for word in nltk.tokenize.word_tokenize(dialogue):
                      word_count[word] += 1
              word_counts[person] = word_count
          return word_counts
      
      if __name__ == '__main__':
          dialogues = get_dialogues('script.txt', ['Sampson', 'Gregory', 'Abraham'])
          word_counts = get_word_counts(dialogues)
          print word_counts
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-11-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-05
        • 2019-04-28
        相关资源
        最近更新 更多