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

如何高效生成元素索引字典及计算二元语料库首词出现次数?

问题2:高效统计Bigram首词的出现次数

核心优化思路

避开低效的手动计数逻辑,选用专门优化的工具处理:

方案1:collections.Counter(标准库最优选择)

Counter是Python为计数场景量身打造的结构,性能远优于手动用dict/defaultdict累加,还支持生成器输入(节省内存):

from collections import Counter

# 如果已有首词列表
first_words = ['You', 'will', 'face', 'many', 'will', 'face']
count_A = Counter(first_words)

# 如果直接从bigram键生成(无需中间列表)
bigrams = [['You', 'will'], ['will', 'face'], ['face', 'many'], ['many', 'defeats'], ['will', 'try']]
count_A = Counter(bigram[0] for bigram in bigrams)

# 获取单个首词的计数
print(count_A['will'])  # 输出2

方案2:pandas(超大规模语料场景)

处理百万级以上语料时,利用pandas的向量化操作能进一步提升速度:

import pandas as pd

first_words = ['You', 'will', 'face', 'many', 'will', 'face']
count_A = pd.Series(first_words).value_counts().to_dict()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 22:40:33