2017-08-07 22 views
0

我正在使用freesound API搜索和下載聲音片段以用於訓練神經網絡。當腳本遇到名稱中包含特殊字符的文件時,它將發出錯誤,腳本將停止。我想下載它帶有特殊字符的文件並繼續搜索。在名稱中使用「/」或「」下載文件時出錯

這裏是我的代碼:(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' 
+0

'if「/」或「\\」或'。'不在sound.name'中:不會做你認爲它的作用。這只是'真的' –

回答

0
if "/" or "\\" or '.' not in sound.name 

只是"/"(truthy)保存執行結果其他表達。由於它是「真實的」,它會在此處停止(短路),並且您始終輸入if

嘗試自然語言不是在Python中編碼的正確方法。

除此之外,請注意,只有有問題的字符這裏有斜槓/反斜槓(你應該測試冒號爲好),但點是一個文件名OK

爲了使其正常工作,我會用any這樣:

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

謝謝。這工作。 –

+0

好的,很高興知道。告訴「它工作」的正確方法是接受答案:http://stackoverflow.com/help/someone-answers –

相關問題