我有以下代码:
def gettextbyxpath(tree, xpath):
node = tree.xpath(xpath)[0]
try:
text = etree.tostring(node, method="text", encoding='UTF-8').strip()
text = re.sub(' +',' ', text)
text = re.sub('\n+','\n', text)
text = re.sub('\n \n','\n', text)
except:
text = 'ERROR'
return text
在最后一行中,我尝试删除只有一个空格的行。实际数据中这样的数量相当多。
当我将上面的代码作为独立测试运行时,它工作正常,但在实际代码中,最后一行根本不执行任何操作!我尝试比较使用和不使用它生成的文件 - 没有差异。
输入示例:
Brand:
777,Royal Lion
Main Products:
battery, 777, carbon zinc, paper jacket,
我正在尝试消除行之间的垂直空白。
对于为什么我的代码会出现这样的行为有什么想法吗?
最佳答案
至于为什么您的代码会按照您所描述的方式运行:您从第二次调用 re.sub
中获得的 text
值不包含您所要的模式尝试在上次调用 re.sub
中替换:
>>> text = re.sub('\n+', '\n', text) # 2nd call to re.sub
>>> text
>>> 'Brand:\n 777,Royal Lion\n Main Products:\n battery, 777, carbon zinc, paper jacket,'
因此,您需要从上次调用 re.sub
的模式中删除第二个 \n
:
text = re.sub('\n ','\n', text)
这将产生:
Brand:
777,Royal Lion
Main Products:
battery, 777, carbon zinc, paper jacket,
替代解决方案
def gettextbyxpath(tree, xpath):
node = tree.xpath(xpath)[0]
try:
text = etree.tostring(node, method="text", encoding='UTF-8').strip()
text = '\n'.join(line.strip() for line in text.split('\n') if line.strip())
except:
text = 'ERROR'
return text
输出
Brand:
777,Royal Lion
Main Products:
battery, 777, carbon zinc, paper jacket,
此方法的不同之处在于,我们不是使用 re.sub
进行连续替换,而是将 etree.tostring
的输出拆分为 \n
。然后,我们过滤结果以排除在调用 .strip()
时减少为空字符串的所有行。这使得我们只剩下具有实际内容的行,并且从左侧和右侧删除了所有空白。为了获得最终结果,我们用一个换行符 (\n
) 连接各行。
关于Python:re.sub 没有改变任何东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22491367/