如何打印文件的所有行,例如在python中用("#")注释的行?
样本数据:
World is suffering from the penidemic due to corona.
#Stay safe #stay home
focus on boosting immunity#stay fit
Pray for all the corona warriors.
我的尝试:
with open('file.txt','r') as f:
b=[line.strip().split() for line in f if not line.startswith(('#'))]
代码的输出包含“ immunity#safe”
我想忽略评论文本。 我不知道如何进行进一步。请帮助,谢谢
分析解答
您可以将str.split()
与maxsplit=1
参数一起使用。
例如:
data = []
with open('file.txt', 'r') as f_in:
for line in f_in:
line = line.split('#', maxsplit=1)[0].strip()
if line:
data.append(line)
print(data)
printf:
['World is suffering from the penidemic due to corona.', 'focus on boosting immunity', 'Pray for all the corona warriors.']