下载nam中带有“/”或“\”的文件时出错

2024-06-28 14:37:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用freesoundapi来搜索和下载声音片段,用于训练神经网络。当脚本遇到名称中有特殊字符的文件时,它将给出一个错误,脚本将停止。我想下载它遇到的特殊字符的文件,并继续搜索

下面是我的代码:(API键在里面,现在才取出来)

import freesound, sys,os


client = freesound.FreesoundClient()
client.set_token("API KEY","token")

results = client.text_search(query="dog", page_size=150, 
fields="id,name,previews")



for sound in results:
    if "/" or "\\" or '.' not in sound.name:
        sound.retrieve_preview(".", sound.name+".mp3")
        print(sound.name)

错误代码:

FileNotFoundError: [Errno 2] No such file or directory: '.\\Dog eating Neck 
of Goose / Chewing / Breaking Bones.mp3'

Tags: or文件namein脚本clienttokenapi
1条回答
网友
1楼 · 发布于 2024-06-28 14:37:10
if "/" or "\\" or '.' not in sound.name

只是"/"(truthy)或其他表达式。因为它是“真实的”,所以它停在这里(短路),你总是进入if

尝试自然语言不是用python编写代码的正确方法

另外,请注意,这里唯一有问题的字符是斜杠/反斜杠(您也应该测试冒号),但dot可以作为文件名

为了让它正常工作,我会像这样使用any

if not any(x in "/\\:" for x in sound.name):

相关问题 更多 >