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

Python列表打印异常求助:仅需输出最终处理后的wordsList

问题描述

需要将单篇文章按11个月份分类,把单词存入wordsList,但当前代码在循环内部多次打印列表,输出了所有中间过程。仅希望打印最终完成的列表(如[['behsud', 'afghanistan', '', 'the', 'first'], [], ['it’s', 'the', 'rare', 'wine'], [], [], [], [], [], [], [], [], []]),而非前8行的中间版本。

代码片段

def process_file(filename):
    file = open(filename, 'r', encoding="utf-8")
    nextL = file.readline()
    wordsList = [[],[],[],[],[],[],[],[],[],[],[]]

    while nextL != '':
        if nextL[0:3] == 'URL':
            url = nextL
            get_week(url)

            nextL = file.readline()

        else:
            for i in nextL:
                while nextL[0:3] != 'URL':
                    aux = ''
                    nextL = nextL.split()
                    for i in nextL:
                        a = i.strip('—;“.”:!,?')
                        aux += a
                        wordsList[get_week(url)].append(aux.lower())

                        #
                        weekly_tokens = print(wordsList)
                        #

                        aux = ''
                        
                    nextL = file.readline()
    file.close()

    return weekly_tokens


def main():
    process_file(get_filename())
    #process_file(filename) ?
    #print(weekly_tokens) ?
main()

当前输出

Enter a file name: articles.txt
[['behsud'], [], [], [], [], [], [], [], [], [], []]
[['behsud', 'afghanistan'], [], [], [], [], [], [], [], [], [], []]
[['behsud', 'afghanistan', ''], [], [], [], [], [], [], [], [], [], []]
[['behsud', 'afghanistan', '', 'the'], [], [], [], [], [], [], [], [], [], []]
[['behsud', 'afghanistan', '', 'the', 'first'], [], [], [], [], [], [], [], [], [], []]
[['behsud', 'afghanistan', '', 'the', 'first'], [], ['it’s'], [], [], [], [], [], [], [], []]
[['behsud', 'afghanistan', '', 'the', 'first'], [], ['it’s', 'the'], [], [], [], [], [], [], [], []]
[['behsud', 'afghanistan', '', 'the', 'first'], [], ['it’s', 'the', 'rare'], [], [], [], [], [], [], [], []]
[['behsud', 'afghanistan', '', 'the', 'first'], [], ['it’s', 'the', 'rare', 'wine'], [], [], [], [], [], [], [], []]

错误分析

  1. 打印时机错误:print(wordsList)被放在最内层的for i in nextL循环中,每处理一个单词就执行一次打印,导致输出所有中间状态的列表。
  2. 变量赋值无效:weekly_tokens = print(wordsList)是错误的,因为print()函数没有返回值(实际返回None),最终返回的weekly_tokens无法拿到有效列表数据。

修正方案

步骤1:移除循环内的打印语句

删除最内层循环里的weekly_tokens = print(wordsList)这一行,避免频繁打印中间结果。

步骤2:返回正确列表并在外部打印

修改process_file函数,让它返回最终的wordsList,然后在main函数中接收并打印这个结果。

修正后的代码

def process_file(filename):
    file = open(filename, 'r', encoding="utf-8")
    nextL = file.readline()
    wordsList = [[],[],[],[],[],[],[],[],[],[],[]]

    while nextL != '':
        if nextL[0:3] == 'URL':
            url = nextL
            get_week(url)
            nextL = file.readline()
        else:
            for i in nextL:
                while nextL[0:3] != 'URL':
                    aux = ''
                    nextL = nextL.split()
                    for i in nextL:
                        a = i.strip('—;“.”:!,?')
                        aux += a
                        wordsList[get_week(url)].append(aux.lower())
                        aux = ''
                    nextL = file.readline()
    file.close()
    # 返回最终处理完成的列表
    return wordsList


def main():
    # 接收函数返回的最终列表
    final_words_list = process_file(get_filename())
    # 打印最终结果
    print(final_words_list)

main()

可选优化建议

使用with语句自动管理文件关闭,避免手动调用file.close()的遗漏风险:

def process_file(filename):
    wordsList = [[],[],[],[],[],[],[],[],[],[],[]]
    # with语句会自动关闭文件
    with open(filename, 'r', encoding="utf-8") as file:
        nextL = file.readline()
        while nextL != '':
            if nextL[0:3] == 'URL':
                url = nextL
                get_week(url)
                nextL = file.readline()
            else:
                for i in nextL:
                    while nextL[0:3] != 'URL':
                        aux = ''
                        nextL = nextL.split()
                        for i in nextL:
                            a = i.strip('—;“.”:!,?')
                            aux += a
                            wordsList[get_week(url)].append(aux.lower())
                            aux = ''
                        nextL = file.readline()
    return wordsList

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 06:10:19