V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
lisisi
V2EX  ›  Python

这一行代码没看懂:为什么把正常的 Print(transcript)放在 except 后面输出?

  •  
  •   lisisi · 7 小时 40 分钟前 · 502 次点击

    模型输出 audio 和 transcript:

    audio_string = ""
    for chunk in completion:
        if chunk.choices:
            if hasattr(chunk.choices[0].delta, "audio"):
                try:
                    audio_string += chunk.choices[0].delta.audio["data"]
                except Exception as e:
                    print(chunk.choices[0].delta.audio["transcript"])
        else:
            print(chunk.usage)
    
    wav_bytes = base64.b64decode(audio_string)
    audio_np = np.frombuffer(wav_bytes, dtype=np.int16)
    sf.write("audio_assistant_py.wav", audio_np, samplerate=24000)
    

    第 7 、8 行:为什么把 print(chunk.choices[0].delta.audio["transcript"]) 放在 Exception 后面输出?

    3 条回复    2025-07-08 14:33:44 +08:00
    lisisi
        1
    lisisi  
    OP
       6 小时 33 分钟前
    ```
    if "data" in chunk.choices[0].delta.audio:
    audio_string += chunk.choices[0].delta.audio["data"]
    elif "transcript" in chunk.choices[0].delta.audio:
    print(chunk.choices[0].delta.audio["transcript"])
    ```
    NoOneNoBody
        2
    NoOneNoBody  
       6 小时 1 分钟前
    except 内的 print 只是取代原有的出错信息,让代码可以继续运行,意义不大,有些人甚至只给个 pass
    如果这段代码是别人写的,这个 print 只是随便打个断点信息,你可以改成你能理解的,或者输出到 log 方便以后查找
    guanzhangzhang
        3
    guanzhangzhang  
       5 小时 56 分钟前
    可能是偷懒选择一个随便思考的解决方式
    关于   ·   帮助文档   ·   自助推广系统   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   2924 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 20ms · UTC 12:30 · PVG 20:30 · LAX 05:30 · JFK 08:30
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.