Python 如何根据名称将文本文件中的单词添加到词典中?

Python 如何根据名称将文本文件中的单词添加到词典中?,python,file,list,dictionary,Python,File,List,Dictionary,我有一个文本文件,里面有《罗密欧与朱丽叶》中第一幕的剧本,我想数一数有人说了多少次一个词 全文如下: 正文中有三个人在讲话:格雷戈里、桑普森和亚伯拉罕 基本上,我想为三位演讲者中的每一位制作三本不同的词典(如果这是最好的方法?)。用人们各自说的单词填充字典,然后计算他们在整个脚本中说每个单词的次数 我该怎么做呢?我想我可以算出词数,但我有点困惑,如何区分谁说了什么,并将其放入3本不同的词典中 我的输出应该是这样的(这不是正确的,只是一个示例): 其中数字是文件中所说单词的频率 现在我已经编写了一

我有一个文本文件,里面有《罗密欧与朱丽叶》中第一幕的剧本,我想数一数有人说了多少次一个词

全文如下:

正文中有三个人在讲话:格雷戈里、桑普森和亚伯拉罕

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

我该怎么做呢?我想我可以算出词数,但我有点困惑,如何区分谁说了什么,并将其放入3本不同的词典中

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

其中数字是文件中所说单词的频率

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


你不必发布精确的代码,只要解释一下我需要做什么,希望我能弄明白。我使用的是Python3。

您不想马上去掉标点符号。前面的冒号加上一个新行,告诉你一个人的引语从哪里开始和结束。这一点很重要,这样你就知道该在哪本词典中添加给定引号中的单词了。您可能需要某种if-else,它会根据当前正在讲话的人添加到不同的词典中

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

下面是一个简单的实现:

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

您可能希望使用一个字典,其中键是名称,值是您所描述的字典
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