例如,我有一个句子。
"He is so .... cool!"
然后我移除所有标点符号,并将其制成列表。
["He", "is", "so", "", "cool"]
我该如何删除或忽略空字符串?
filter
函数,并将参数设置为 None
以过滤掉所有等于 False
的元素(包括空字符串)。>>> lst = ["He", "is", "so", "", "cool"]
>>> filter(None, lst)
['He', 'is', 'so', 'cool']
需要注意的是,在Python 2中filter
返回一个列表,但在Python 3中返回一个生成器。您需要将其转换为列表,或使用列表推导式解决方案。
False
ish值包括:
False
None
0
''
[]
()
# and all other empty containers
['']
会发生什么? - tumultous_roosterTrue
中有一个 False
,嗯 - tumultous_rooster你可以像这样进行筛选
orig = ["He", "is", "so", "", "cool"]
result = [x for x in orig if x]
您可以使用 filter
。在Python 3中, filter
返回一个生成器,因此 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']
>>> "He is so .... cool!".replace(".", "").split(" ")
['He', 'is', 'so', '', 'cool!']
.split(" ")
来分割空格字符。然而,如果省略 split
的参数,会发生以下情况:>>> "He is so .... cool!".replace(".", "").split()
['He', 'is', 'so', 'cool!']
引用文档:
如果未指定sep或为None,则将应用不同的拆分算法:连续的空白字符被视为单个分隔符,并且如果字符串具有前导或尾随空格,则结果将不包含开头或结尾的空字符串。
因此,您真的不需要费心去看其他答案(除了Blender的答案,这是一种完全不同的方法),因为split可以帮助您完成工作!
>>> 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']
w.strip(punctuation)
,最好使用 l = [w.strip(punctuation) for w in text.split()]
然后再使用 [w for w in l if w]
... - glglglx = ["He", "is", "so", "", "cool"]
x = [str for str in x if str]
>>> ['He', 'is', 'so', 'cool']
str_list = list(filter(None, str_list)) # fastest
lst = ["He", "is", "so", "", "cool"]
lst = list(filter(str.strip, lst))
filter
来实现这个功能。a = ["He", "is", "so", "", "cool"]
filter(lambda s: len(s) > 0, a)