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

如何在Python中为每个重复的文章编码单独计数并标记序号?

问题解决方法

你的核心问题是用了全局计数变量,导致所有编码的计数累加,无法单独统计每个编码的出现次数。只需用一个字典来跟踪每个编码的独立计数即可。

修改后的代码

# 初始化字典,用于记录每个编码的当前计数
article_counts = {}

for row in range(rbegin, rfinish):
    for col in range(1, 2):  
        char = get_column_letter(col)
        article_number = ws[char + str(row)].value
        new_article_number = article_number[:-4] 
        for subdir, dirs, files in os.walk(articles_path): 
            for folder_article in files:  
                if folder_article.__contains__(new_article_number):
                    # 针对当前编码获取计数,不存在则从0开始
                    current_count = article_counts.get(new_article_number, 0) + 1
                    article_counts[new_article_number] = current_count
                    
                    article_copy = os.path.join(subdir, folder_article)  
                    shutil.copy2(article_copy, paired_articles_path)  
                    updated_article = folder_article[:10] # 因为第一列的编码是10个字符
                    print(f"{new_article_number};{updated_article}_{current_count}")

关键修改点

  • 新增article_counts字典,键为编码名称,值为该编码当前的计数
  • 替换全局的article_found_count为针对每个编码的current_count,每次获取当前编码的已有计数(默认0)加1,再更新字典
  • 输出时使用current_count替代原全局变量,确保每个编码的计数从1开始独立累加

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 05:16:19