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

2024-10-04 01:23:05 发布

您现在位置:Python中文网/ 问答频道 /正文

朱丽叶和朱丽叶的剧本我有多少次要从《罗密欧》的剧本中找到。在

以下是文本:http://pastebin.com/X0gaxAPK

文中有三个人在发言:格雷戈里、桑普森和亚伯拉罕。在

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

我该怎么做呢?我想我能算出字数,但我有点困惑,不知道如何区分谁说了什么,并把它编入每个人的3个不同的词典。在

我的输出应该如下所示(这不是正确的,而是一个示例):

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

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

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

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


Tags: 方法代码文本脚本comhttp字典单词
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
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())

输出示例:

^{pr2}$

你不想马上去掉标点符号。一个新行前面的冒号告诉你一个人的引语开始和结束的位置。这一点很重要,这样你就可以知道在哪本词典中要将引用的单词追加到哪个词典中。你可能会需要一些if-else,它会根据当前说话的人而附加到不同的字典中。在

相关问题 更多 >