【问题标题】:Reading only the words of a specific speaker and adding those words to a list只阅读特定演讲者的单词并将这些单词添加到列表中
【发布时间】:2023-03-28 03:48:01
【问题描述】:

我有一个成绩单,为了对每个发言者进行分析,我只需要将他们的话添加到一个字符串中。我遇到的问题是每一行都不以演讲者姓名开头。 这是我的文本文件的 sn-p

BOB: blah blah blah blah
blah hello goodbye etc.

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

BOB:blah blah blah
blah blah blah
blah.

我只想收集所选说话者(在本例中为 bob)所说的单词,并将它们添加到字符串中,并排除来自 jerry 和其他说话者的单词。对此有何想法?

编辑:段落之间和任何新演讲者开始之前都有换行符。

【问题讨论】:

  • “每一行都不以演讲者姓名开头”——所以保留一个变量currentSpeaker,并且只有在开头附近有一个冒号时才更新它。
  • @Rami - 当您编辑此问题时,您从文件示例中删除了换行符,但这些换行符的存在是此问题中的主要问题。
  • 说话人换人时总是有空行吗?
  • 您可以考虑将currentSpeaker 设置为无,以防有一些描述性文字(例如:JERRY 离开房间)。但您必须能够区分该描述性文本和演讲者的后续文本。
  • 你的文本文件怎么样?每次新扬声器启动时,您都有一个 \n 字符?您需要找到“规则”以了解新演讲者何时开始讲话......

标签: python string file


【解决方案1】:

使用正则表达式是最好的方法。由于您将多次使用它,因此您可以通过在使用它来匹配每一行之前对其进行编译来节省一些处理时间。

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": ['.............................................', '...............']
}

【讨论】:

    【解决方案2】:

    每次有发言者开始发言,保持current_speaker,根据这个发言者决定做什么。朗读台词,直到说话人发生变化。

    【讨论】:

      猜你喜欢
      • 2020-09-19
      • 1970-01-01
      • 2022-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-10
      相关资源
      最近更新 更多