python从fi删除行

2024-09-30 20:21:10 发布

您现在位置:Python中文网/ 问答频道 /正文

问题:

我试图从我的.txt文件中删除空行。 因为我的.txt文件是Python通过HTML下载生成的,我想把它们保存在某个位置,所以我不得不使用Os.path.join操作系统. 在

这是删除所有标记并仅保留标记内部后将HTML保存在该位置的代码:

cntent = re.sub('<[^>]+>',"\n", str(cntent))
with open(os.path.join('/Users/Brian/Documents/test',titles), "wb") as file: 
        file.writelines(str(cntent))

我怎样才能做到这一点?在

文件的结果:

^{pr2}$

我尝试了:

filtered = filter(lambda x: not re.match(r'^\s*$', x), original)

期望结果

 Productspecificaties
 Uiterlijke Kenmerken
 Gewicht
 185Gr

请注意,在第一行代码re.sub...我使用“\n”,否则根本就没有空格。


Tags: 文件path代码标记retxtoshtml
2条回答

不需要使用正则表达式:

cntent = re.sub('<[^>]+>',"\n", str(cntent))
with open(os.path.join('/Users/Brian/Documents/test', titles), "wb") as f: 
    f.writelines(line for line in cntent.splitlines(True) if line.strip())

^{}在字符串的开头和结尾处去掉空格(包括换行符)。对于只包含空格的行,它将返回空字符串;该字符串的计算结果为false。在

^{}withTrue用于拆分行,但不排除新行。在

试试这个模式
^\s+w/m选项
Demo

相关问题 更多 >