只读特定说话人的话并将这些话添加到列表中

2024-04-19 02:57:42 发布

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

我有一个抄本,为了对每个说话人进行分析,我只需要将他们的话添加到一个字符串中。我遇到的问题是每一行都不是以说话者的名字开头的。 这是我的文本文件的一个片段

BOB: blah blah blah blah
blah hello goodbye etc.

JERRY:.............................................
...............

BOB:blah blah blah
blah blah blah
blah.

我只想收集所选演讲者(在本例中是bob)所说的单词,并将它们添加到字符串中,排除jerry和其他演讲者的单词。有什么想法吗?你知道吗

在编辑:有在任何新的段落开始之前。你知道吗


Tags: 字符串helloetc名字单词bob演讲者blah
2条回答

使用正则表达式是最好的方法。由于您将多次使用它,因此可以在使用它匹配每一行之前先编译它,从而节省一些处理时间。你知道吗

import re

speaker_words = {}
speaker_pattern = re.compile(r'^(\w+?):(.*)$')

with open("transcript.txt", "r") as f:
        lines = f.readlines()
        current_speaker = None
        for line in lines:
                line = line.strip()
                match = speaker_pattern.match(line)
                if match is not None:
                        current_speaker = match.group(1)
                        line = match.group(2).strip()
                        if current_speaker not in speaker_words.keys():
                                speaker_words[current_speaker] = []
                if current_speaker:
                        # you may want to do some sort of punctuation filtering too
                        words = [word.strip() for word in line.split(' ') if len(word.strip()) > 0]
                        speaker_words[current_speaker].extend(words)

print speaker_words

这将输出以下内容:

{
    "BOB": ['blah', 'blah', 'blah', 'blah', 'blah', 'hello', 'goodbye', 'etc.', 'blah', 'blah', 'blah', 'blah', 'blah', 'blah', 'blah.'],
    "JERRY": ['.............................................', '...............']
}

每次演讲者开始讲话时,保留当前的演讲者,并根据该演讲者决定要做什么。把台词读到说话人换了为止。你知道吗

相关问题 更多 >