【发布时间】:2018-05-30 13:50:24
【问题描述】:
我有这个嵌套的字符串列表,它处于清理的最后阶段。我想用空格替换嵌套列表中的非字母或创建一个没有非字母的新列表。这是我的清单:
list = [['hello', 'mr.', 'smith', ',', 'how', 'are', 'you', 'doing', 'today', '?'], ['the', 'weather', 'is', 'great', ',', 'and', 'python', 'is', 'awesome', '.'], ['the', 'sky', 'is', 'pinkish-blue', '.'], ['you', 'should', "n't", 'eat', 'cardboard', '.']]
这就是我想用它来清理它的模式
pattern = re.compile(r'\W+')
newlist = list(filter(pattern.search, list))
print(newlist)
代码不起作用,这是我得到的错误:
Traceback (most recent call last):
File "/Users/art/Desktop/TxtProcessing/regexp", line 28, in <module>
newlist = [list(filter(pattern.search, list))]
TypeError: expected string or bytes-like object
我知道list 不是字符串,而是字符串列表,我该如何解决?
非常感谢任何帮助!
【问题讨论】:
-
您最初是如何获得这份清单的?在标记句子和单词时,您可能已经清除了非字母标记。
-
永远不要将变量调用到内置函数(
list、set、dict等)。 -
您不能在列表列表上执行 pattern.search。
-
尝试
[list(filter(pattern.search, sl)) for sl in your_list],不要命名变量list,否则您将无法使用该函数。
标签: python regex string python-3.x filter