当前位置: 代码迷 >> 综合 >> with open() 去除空行、首尾空格文件 常见读取自定义函数
  详细解决方案

with open() 去除空行、首尾空格文件 常见读取自定义函数

热度:14   发布时间:2024-02-21 12:36:52.0

一、读取普通的txt文件

import pandas as pd
def load_comments(self,comments_path):"""加载文件【①去除空行数据 ②去除首尾空格】至Series中,保存每段文本所对应的行号:param comments_path: 文件的路径:return: Series"""# 将数据保存至 Series 中comments_ser = pd.Series()try:with open(comments_path,'r',encoding='utf-8-sig') as w:for row,line in enumerate(w.readlines()):# 对每一行的数据前后去除空格line = line.strip()# 判断去除空格后的数据是否有内容,只要有数据的内容【去除空行数据】if line:# 添加行号row_index = row + 1comments_ser.loc[row_index] = lineexcept Exception as e:with open(comments_path, 'r', encoding='gbk') as w:for row, line in enumerate(w.readlines()):# 对每一行的数据前后去除空格line = line.strip()# 判断去除空格后的数据是否有内容,只要有数据的内容【去除空行数据】if line:# 添加行号row_index = row + 1comments_ser.loc[row_index] = linereturn comments_ser

二、

 

 

 

 

 

  相关解决方案