7

私は基本的に、次のような文を含む文字列のリストを取得しようとしています:

sentence = ['Here is an example of what I am working with', 'But I need to change the format', 'to something more useable']

それを次のように変換します。

word_list = ['Here', 'is', 'an', 'example', 'of', 'what', 'I', 'am',
'working', 'with', 'But', 'I', 'need', 'to', 'change', 'the format',
'to', 'something', 'more', 'useable']

私はこれを使ってみました:

for item in sentence:
    for word in item:
        word_list.append(word)

各文字列を取り、その文字列の各項目を word_list に追加すると思いましたが、出力は次の行に沿ったものです。

word_list = ['H', 'e', 'r', 'e', ' ', 'i', 's' .....etc]

愚かな間違いを犯していることはわかっていますが、理由がわかりません。誰か助けてもらえますか?

4

5 に答える 5

18

str.split()各文字列を単語に分割する必要があります。

word_list = [word for line in sentence for word in line.split()]
于 2011-12-12T17:55:08.607 に答える
7

だけ.split.join:

word_list = ' '.join(sentence).split(' ')
于 2011-12-12T17:55:14.717 に答える
4

単語を区別する方法を教えていません。デフォルトでは、文字列を反復処理すると、単純に文字が反復処理されます。

.split(' ')文字列をスペースで分割するために使用できます。したがって、これは機能します:

for item in sentence:
    for word in item.split(' '):
        word_list.append(word)
于 2011-12-12T17:55:29.300 に答える
2
for item in sentence:
    for word in item.split():
        word_list.append(word)
于 2011-12-12T17:56:01.953 に答える
-1

文を単語に分割する:

print(sentence.rsplit())
于 2017-12-12T13:10:48.967 に答える