python从文件中删除行

use*_*459 2 python regex string file str-replace

题:

我想从我的.txt文件中删除空行.因为我的.txt文件是由Python通过HTML下载生成的,我想将它们保存在某个位置,所以我必须使用Os.path.join.

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

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

我怎么能实现这个目标?

文件的结果:

Productspecificaties




Uiterlijke kenmerken















Gewicht










185 g
Run Code Online (Sandbox Code Playgroud)

我尝试了什么:

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

期望的结果

 Productspecificaties
 Uiterlijke Kenmerken
 Gewicht
 185Gr
Run Code Online (Sandbox Code Playgroud)

请注意,在第一行代码中re.sub...我使用"\n",因为否则根本就没有空格.

fal*_*tru 5

您不需要使用正则表达式:

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())
Run Code Online (Sandbox Code Playgroud)

str.strip()在字符串的开头和结尾处去除空格(包括换行符).对于仅包含空格的行,它将返回空字符串; 被评估为假值.

str.splitlineswith True用于分割线条,但不排除新线条.