You need to enable JavaScript to run this app. Python处理古腾堡《麦克白》文本:按角色发言标记拆分的实现问题
优惠活动
大模型
产品
解决方案
定价
更多

Python处理古腾堡《麦克白》文本:按角色发言标记拆分的实现问题

麦克白角色发言识别与拆分实现

核心逻辑

先区分带句号的词是否为角色发言标记:如果词末尾带句号,且去掉句号后的前缀匹配已知角色名的开头,就保留该句号作为拆分标记,其余所有标点全部删除,最终按标记点拆分不同角色的发言内容。

完整实现代码

import requests
import string

# 获取《麦克白》文本
response = requests.get('https://www.gutenberg.org/cache/epub/2264/pg2264.txt')
full_text = response.text
macbeth = full_text[16648:]

# 按空格拆分原始词列表
words_raw = macbeth.split()

# 已知角色名列表
character_names = ["duncan", "malcolm", "donalbaine", "macbeth", "banquo", "macduff", "lenox", "rosse", "menteth", "angus", "cathnes", "fleance", "seyward", "seyton", "boy", "lady", "messenger", "wife"]

# 单词语处理函数:区分角色标记和普通单词做不同清洗
def process_word(word):
    # 先判断是否为角色发言标记(末尾带句号)
    if word.endswith('.'):
        word_prefix = word[:-1].lower()
        for name in character_names:
            # 匹配规则:前缀匹配角色名开头,且前缀长度≥2避免误判序号类的带点词
            if name.startswith(word_prefix) and len(word_prefix) >= 2:
                # 是角色标记,仅去除除了句号之外的标点,转小写
                cleaned = word.strip(string.punctuation.replace('.', '')).lower()
                return cleaned
    # 非角色标记,去除所有标点转小写
    cleaned = word.strip(string.punctuation).lower()
    return cleaned

# 清洗全量单词
words_cleaned = [process_word(w) for w in words_raw if process_word(w)]

# 按角色标记拆分发言
speeches = []
current_speaker = None
current_content = []

for word in words_cleaned:
    if word.endswith('.'):
        # 检查是否为角色标记
        word_prefix = word[:-1]
        for name in character_names:
            if name.startswith(word_prefix):
                # 保存上一段发言
                if current_speaker and current_content:
                    speeches.append({
                        "speaker": current_speaker,
                        "content": " ".join(current_content)
                    })
                # 更新当前发言者为完整角色名
                current_speaker = name
                current_content = []
                break
        else:
            # 非角色标记的带点词加入发言内容
            current_content.append(word)
    else:
        # 普通单词加入发言内容
        current_content.append(word)
# 保存最后一段发言
if current_speaker and current_content:
    speeches.append({
        "speaker": current_speaker,
        "content": " ".join(current_content)
    })

效果验证代码

# 输出前5段发言检查效果
for idx, speech in enumerate(speeches[:5]):
    print(f"第{idx+1}段发言 发言者:{speech['speaker']}")
    print(f"内容片段:{speech['content'][:100]}...\n")

规则说明

  • 前缀匹配逻辑支持自动识别缩写、全名两种角色标记格式,自动映射为列表中的完整角色名
  • 长度≥2的限制可以避免把场景序号(如1.、2.)误判为角色标记
  • 除角色标记的句号外,其余所有标点都会被清除,不会干扰后续文本分析

内容的提问来源于stack exchange,提问作者zelfde

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 19:27:06