You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

统计情绪连续状态时,如何准确计数所有重叠子串?

情绪字符串连续状态统计方案

核心逻辑

要解决重叠子串计数不准的问题,核心是逐个比较相邻字符,而非依赖子串匹配。连续n个相同字符(比如"111")对应的连续保持次数是n-1次,遍历相邻字符对就能准确统计所有状态。

SAS实现步骤

假设你的数据集名为mood_data,情绪变量为mood:

1. 拆分字符串为单个字符

用数组把每个情绪字符串的字符拆分到单独变量中,适配最长9位的字符串:

data mood_split;
    set mood_data;
    array m[9] $1 m1-m9;
    do i = 1 to length(mood);
        m[i] = substr(mood, i, 1);
    end;
run;

2. 统计连续保持与变化情况

遍历相邻字符对,分别统计每种情绪的连续保持次数,以及总变化次数:

data mood_stats;
    set mood_split;
    STATIC_11 = 0; STATIC_22 = 0; STATIC_33 = 0;
    CHANGE_COUNT = 0;
    
    if length(mood) >= 2 then do;
        prev_char = m1;
        do i = 2 to length(mood);
            if m[i] = prev_char then do;
                select(prev_char);
                    when('1') STATIC_11 + 1;
                    when('2') STATIC_22 + 1;
                    when('3') STATIC_33 + 1;
                end;
            end;
            else do;
                CHANGE_COUNT + 1;
                prev_char = m[i];
            end;
        end;
    end;
    
    total_static = STATIC_11 + STATIC_22 + STATIC_33;
    drop i prev_char m1-m9;
run;

结果验证

  • 对于Betty的111213,输出STATIC_11=2,CHANGE_COUNT=3,符合需求
  • 对于Albert的112132,输出STATIC_11=1,CHANGE_COUNT=4,统计准确

通用代码示例(Python)

如果用Python处理,逻辑完全一致:

def calculate_mood_stats(mood_str):
    stats = {
        'static_11': 0,
        'static_22': 0,
        'static_33': 0,
        'change_count': 0
    }
    if len(mood_str) < 2:
        return stats
    
    prev_char = mood_str[0]
    for curr_char in mood_str[1:]:
        if curr_char == prev_char:
            stats[f'static_{prev_char}{curr_char}'] += 1
        else:
            stats['change_count'] += 1
        prev_char = curr_char
    return stats

# 测试用例
print(calculate_mood_stats("111213"))  # {'static_11': 2, 'static_22': 0, 'static_33': 0, 'change_count': 3}
print(calculate_mood_stats("112132"))  # {'static_11': 1, 'static_22': 0, 'static_33': 0, 'change_count': 4}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 15:30:05