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

Python多输入Bigram计数代码NameError问题的原因与修复

解决Python Bigram统计程序的首次空输入错误问题

Hey there! Let's break down why your code throws an error when the first input is empty, and how to fix it.

错误原因分析

Looking at your original code, the text variable is defined inside the while a: loop. When you first enter nothing (just hit enter), a becomes an empty string, so the while a: condition fails immediately—meaning the loop never runs at all.

That leaves text completely uncreated, and when your code tries to run for bigram in text: later, Python has no idea what variable you're referring to. Hence the NameError: name 'text' is not defined message.

修复方案

We need to make sure text exists no matter what, plus clean up some inefficient logic along the way. Here's the step-by-step fix:

  1. 提前初始化text变量:在循环开始前就把text设为空列表,确保无论用户是否输入内容,变量都存在。
  2. 逐行生成Bigram:原代码每次循环都重新遍历所有输入行生成Bigram,效率很低。改成处理每行输入时直接生成该行的Bigram并添加到text中。
  3. 跳过无效空行:如果用户输入空行(非首次),直接跳过,避免生成无效的Bigram。

修复后的代码

newlist = []
text = []  # 提前初始化text,避免NameError
a = input("Line: ").lower()

while a:
    words = a.split()
    # 只有当行内至少有2个单词时才生成Bigram
    if len(words) >= 2:
        line_bigrams = zip(words[:-1], words[1:])
        text.extend(line_bigrams)
    a = input("Line: ").lower()

# 将二元组转为字符串并统计频次
for bigram in text:
    newbigram = ' '.join(bigram)
    newlist.append(newbigram)

my_dict = {i: newlist.count(i) for i in newlist}
# 排序并输出出现次数>1的结果
for words in sorted(my_dict):
    if my_dict[words] > 1:
        print(f"{words}: {my_dict[words]}")

关键改进说明

  • 提前初始化text = []:即使首次输入为空,text仍是一个空列表,后续的循环只会跳过,不会触发错误。
  • 逐行处理Bigram:避免了重复遍历所有输入内容,提升了代码效率。
  • 增加单词数量检查:防止对单单词行生成无效Bigram,让代码逻辑更严谨。

测试这个代码:如果首次直接按回车,程序会优雅退出而不报错;正常输入时,输出结果和预期完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:27:31