我有一个相当复杂的问题,我想知道你们中的任何编码向导是否能够帮助我:p
我想通过一个 lambda 表达式使用两个正则表达式模式。
该代码应用于熊猫数据框的一列。
我们遍历列中的所有元素。如果字符串包含 '[' ,方括号,则必须执行一个正则表达式模式。如果字符串不包含方括号,则必须执行另一个正则表达式模式。
可以在下面找到两个工作正则表达式模式。
目前它们是分开的,但我想将它们结合起来。
我有以下代码可以正常工作:
chunk['http'] = chunk.loc[chunk['Protocol'] == 'HTTP', 'Information'].apply(
lambda x: re.sub(r'\b[^A-Z\s]+\b', '', x))
chunk['http'] = chunk.loc[chunk['Protocol'] == 'HTTP', 'Information'].apply(
lambda x: re.sub(r'\[(.*?)\]', '', x))
第一个表达式仅保留 CAPS 中的值。第二个表达式只保留方括号之间的值。
我试图在下一段代码中将它们结合起来:
chunk['http'] = chunk.loc[chunk['Protocol'] == 'HTTP', 'Information'].apply(
lambda x: re.sub(r'\b[^A-Z\s]+\b', '', x)) \
if '[' in x == False\
else re.sub(r'\[(.*?)\]', '', x)
但是,这会返回以下错误:
NameError: free variable 'x' referenced before assignment in enclosing scope
你放错了括号。它应该是
chunk['http'] = chunk.loc[chunk['Protocol'] == 'HTTP', 'Information'].apply(
lambda x: re.sub(r'\b[^A-Z\s]+\b', '', x) \
if '[' in x == False\
else re.sub(r'\[(.*?)\]', '', x))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句