2017-09-08 27 views
0

繼發現是我的代碼,我執行ORD()預期的字符,但長度爲0的字符串在Python代碼

https://github.com/federico-terzi/gesture-keyboard/blob/master/learn.py

執行我收到代碼後,

文件 「learn.py」 57行,在

number = ord(category) -ord('a') 

TypeError: ord() expected a character, but string of length 0 found

我該如何解決?

+0

通過將東西放入'category'中,這似乎是一個空列表。 – GPhilo

+0

另外,請閱讀[如何寫好問題的指導方針](https://stackoverflow.com/help/how-to-ask),代碼應該都在問題中,應避免與github的鏈接(因爲他們可能隨時破壞) – GPhilo

+0

我是這個世界的新手,所以請原諒我的錯誤。它迫切需要解決查詢問題。下次會照顧:) –

回答

0

項目數據目錄包含許多文件,其文件名以_開頭,如_sample_t10_34.txt

因此,在你的代碼

for path, subdirs, files in os.walk(root): 
    for name in files: 
     category = name.split("_")[0] # here category = '' 

現在的下一行是:

number = ord(category) - ord("a") 

這裏ord()需要長度爲1 str類型的參數,你得到這個錯誤,因爲類別將某個是一個空字符串'',當名稱爲_sample_t10_34.txt的文件被讀取時。

你可以做的是跳過以_開頭的文件,通過檢查if statement文件是否不以_開頭。

for path, subdirs, files in os.walk(root): 
    for name in files: 
     if not name.startswith('_'): 
      # code here after if statement 
      category = name.split("_")[0] 
      number = ord(category) - ord("a") 
      # rest of code.. 
+0

我試過你的解決方案,但我得到新的錯誤,IndentationError:unindent不匹配任何外部縮進級別 –

+0

哪一行? – Bijoy

+0

如果我把, 如果不是name.startswith('_'): 前行「文件名= os.path.join(路徑,名稱)」,那麼我越來越, 文件「learn.py」,第47行 filename = os.path.join(路徑,名稱) ^ IndentationError:預計有一個縮進塊 –

1

看着你掛碼,category來自

category = name.split("_")[0] 

name來自:

for path, subdirs, files in os.walk(root): 
    for name in files: 

所以我猜測,你有一個前導下劃線的文件名。將此字符串拆分爲'_',這將爲列表的第一個值提供一個空字符串。示例:

s = '_abc_test.txt' 
s.split('_') 
# returns: 
['', 'abc', 'test.txt'] 

這是第零個元素,它是傳遞到ord的空字符串。

+0

你說得對。你能幫我嗎?我應該在代碼中進行更改以使其工作?我的示例文件名是「a_sample_0_1」,它繼續串聯。 –

相關問題