本文主要記錄了將中文字符串轉換為list的過程,其中我們使用了keras preprocessing中的text_to_word_sequence方法。這個方法是完全適配中文的。需要注意的是,中文語料一般字符之間是沒有空格分割的,這與英文是不同的。如下所示,如果我們直接進行轉換,由于沒有空格分詞,會將字符串默認為一個字符。
from tensorflow.keras.preprocessing.text import text_to_word_sequence
text = '我是人'
token = text_to_word_sequence(text)
print(token)
print(type(token))
print(token[0])
運行結果如下 :
['我是人']
<class 'list'>
我是人
要解決這個問題,我們只需要在轉換之前首先在每個中文字符后加上一個空格進行分割就可以。
from tensorflow.keras.preprocessing.text import text_to_word_sequence
text = '我是人'
# 使用join方法在每個中文字符后加入空格
text = ' '.join(text)
token_h = text_to_word_sequence(text)
print(token_h)
print(type(token_h))
print(token_h[0])
這樣我們就可以將’我是人’三個字組成的字符串轉換為一個有三個元素的list了。
輸出結果如下 :
['我', '是', '人']
<class 'list'>
我