たとえば、私は文を持っています
"He is so .... cool!"
次に、句読点をすべて削除してリストにします。
["He", "is", "so", "", "cool"]
空の文字列を削除または無視するにはどうすればよいですか?
このようにフィルタリングできます
orig = ["He", "is", "so", "", "cool"]
result = [x for x in orig if x]
または、 を使用できますfilter
。Python 3filter
では、ジェネレーターが返さlist()
れるため、リストに変換されます。これはpython 2.7でも機能します
result = list(filter(None, orig))
リスト内包表記を使用できます。
cleaned = [x for x in your_list if x]
正規表現を使用して単語を抽出しますが:
>>> import re
>>> sentence = 'This is some cool sentence with, spaces'
>>> re.findall(r'(\w+)', sentence)
['This', 'is', 'some', 'cool', 'sentence', 'with', 'spaces']
>>> from string import punctuation
>>> text = "He is so .... cool!"
>>> [w.strip(punctuation) for w in text.split() if w.strip(punctuation)]
['He', 'is', 'so', 'cool']
リスト内包表記を使用して、空の文字列を非常に簡単に除外できます。
x = ["He", "is", "so", "", "cool"]
x = [str for str in x if str]
>>> ['He', 'is', 'so', 'cool']
Python 3 はiterator
fromfilter
を返すため、list() の呼び出しでラップする必要があります。
str_list = list(filter(None, str_list)) # fastest
でこれを行うことができますfilter
。
a = ["He", "is", "so", "", "cool"]
filter(lambda s: len(s) > 0, a)