파이썬은 txt 파일을 csv 파일로 변환합니다.

머리말

오늘 또 비인기 대본이 나왔어요! txt 파일의 데이터를 읽고 csv 파일로 변환합니다.
예를 들어 다음 파일은 추출할 데이터를 정기적으로 배포하기 시작하고 추출은 세 번째 줄부터 시작하여 데이터를 처리하고 최종적으로 출력합니다.
여기에 이미지 설명 삽입

코드

설명하다:

  1. 다음 코드는 데이터를 추출할 뿐만 아니라 처리 단계도 포함합니다.처리 방법은 공개되지 않으며 from utils.feature_process import FeatureProcess내 사용자 지정 라이브러리입니다.
  2. plot_flag처리된 데이터를 폴더에 표시할 수 있으며 False로 설정하면 그리기가 수행되지 않습니다.
  3. 메인에 소스 파일을 먼저 설정한 후 저장 위치를 ​​설정합니다.
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from utils.feature_process import FeatureProcess  # 自定义的特征处理函数

plot_flag = True


class txt2csv:
    def __init__(self, source_dir, save_dir):

        self.source_dir = source_dir
        self.save_dir = save_dir

    def process(self):
        txt_data = os.listdir(self.source_dir)
        for one_data in txt_data:

            self.csv_date = pd.DataFrame(columns=['frames', 'wratio', 'cvalue', 'kangle'])
            self.arr_data = np.zeros((1, 4))

            self.feature_process = FeatureProcess()

            with open(os.path.join(self.source_dir, one_data), 'r') as f:
                # 读取每个文件夹的数据
                lines = f.readlines()
                for line in lines:
                    num = line.split(',')
                    if len(num) <= 1:
                        continue

                    # 处理数据
                    frame = num[0]
                    bounding_box = num[2:]
                    feature_list = self.feature_process.feature_extraction([240, 320], bounding_box)

                    # 存储数据
                    self.arr_data[0][0] = frame
                    self.arr_data[0][1] = feature_list[0]
                    self.arr_data[0][2] = feature_list[1]
                    self.arr_data[0][3] = feature_list[2]

                    # 追加方式填充上数据
                    one_row_data = pd.DataFrame(self.arr_data, columns=['frames', 'wratio', 'cvalue', 'kangle'])
                    self.csv_date = self.csv_date.append(one_row_data, ignore_index=True)

            self.csv_date.to_csv(os.path.join(self.save_dir, one_date.split('.')[0] + '.csv'), index=False)
            if plot_flag:
                # 拿起画板
                fig = plt.figure()

                # 在画板上贴上画纸
                ax1 = fig.add_subplot(111)
                # 画图显示 True显示,False不显示
                ax1.scatter(self.csv_date['frames'], self.csv_date['cvalue'])

                plt.show()


if __name__ == '__main__':
    # 读取源文件
    tc = txt2csv(r'./annotation_files', '.')  
    # 进行转化和存储
    tc.process()

파일 디렉토리 구조

여기에 이미지 설명 삽입

결과를 csv로 표시하기만 하면 됩니다.

여기에 이미지 설명 삽입

추천

출처blog.csdn.net/weixin_42442319/article/details/128473447