Skip to content

CHICPRO

  • Life Log
  • Cycling Log
  • Photo Log
    • Portrait
    • Landscape
    • Flower
    • Etc
  • Coding Log
  • Information

[Python] 파일에서 필요한 데이터를 추출해 파일로 저장하기 #2

2017-03-10 by 편리

이전에 작성했던 코드를 다시 한번 수정했다. 별다른 것은 없고 퍼포먼스 체크를 위해 실행 시간을 출력하는 부분을 상점ID별로 정보를 출력하도록 수정했다.

# _*_ coding: utf-8 _*_

from multiprocessing import Process
import time
import datetime
import locale

seller = []
exclude = []
datas = []

def get_exce_time(start, end):
    return datetime.timedelta(seconds=(end - start))

def number_format(num, places=0):
    """Format a number according to locality and given places"""
    locale.setlocale(locale.LC_ALL, "")
    return locale.format("%.*f", (places, num), True)

def file_read():
    start = time.time()

    results = {}

    f = open('seller_id.txt', 'r', encoding="utf-8")
    lines = f.readlines()
    f.close()

    for line in lines:
        str = line.split("\t")
        id = str[4].strip()

        if id not in seller:
            seller.append(id)

    results['seller'] = seller

    f = open('exclude_item_id.txt', 'r', encoding="utf-8")
    lines = f.readlines()
    f.close()

    for line in lines:
        str = line.strip()

        if str not in exclude:
            exclude.append(str)

    results['exclude'] = exclude

    f = open('AllDataBasedOnDB.dat', 'r', encoding="utf-8")
    datas = f.readlines()
    f.close()

    results['datas'] = datas

    end = time.time()
    print("File Reading Time : {0}".format(get_exce_time(start, end)))

    return results

def find_item_code(data, process, idx, limit):
    seller = data['seller']
    exclude = data['exclude']
    datas = data['datas']

    for k, s_id in enumerate(seller):
        start = time.time()
        item = []

        if k % process != idx:
            continue

        for line in datas:
            if limit > 0 and len(item) == limit:
                break

            if line.find(s_id) == -1:
                continue

            str = line.split("\t")
            code = str[0].strip()

            if code not in exclude and code not in item:
                item.append(code)

        # txt 파일생성
        f = open('./out/' + s_id + '.txt', 'w')
        f.writelines(map(lambda x: x + "\n", item))
        f.close()

        end = time.time()
        print("{0} Process #{1} Running Time : {2} Count: {3}".format(s_id, idx, get_exce_time(start, end), number_format(len(item))))

if __name__ == '__main__':
    data = file_read()

    # 실행 프로세스 수
    process = 4

    # 추출한 레코드 수 0으로 설정하면 모든 레코드 추출
    limit = 0

    procs = [Process(target=find_item_code, args=((data, process, i, limit,))) for i in range(process)]
    for p in procs: p.start()

이젠 이 코드를 가지고 Class로 변경하는 걸 해보고 싶은데.. 언제가 될지는 아직 모르겠다.

Post navigation

Previous Post:

[Python] 파일에서 필요한 데이터를 추출해 파일로 저장하기

Next Post:

2017년 3월 12일 양수역

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Recent Posts

  • php 배열 연산에서 + 와 array_merge 의 차이
  • pcntl_fork 를 이용한 다중 프로세스 실행
  • 아이폰 단축어를 이용하여 주중 공휴일엔 알람 울리지 않게 하기
  • 구글 캘린더 전체일정 재동기화
  • OpenLiteSpeed 웹서버에 HTTP 인증 적용
  • OpenLiteSpeed 웹어드민 도메인 연결
  • WireGuard를 이용한 VPN 환경 구축
  • Ubuntu 22.04 서버에 OpenLiteSpeed 웹서버 세팅
  • 맥 vim 세팅
  • 우분투 시스템 터미널쉘 zsh 로 변경

Recent Comments

  • 편리 on 업무관리용 그누보드 게시판 스킨
  • 임종섭 on 업무관리용 그누보드 게시판 스킨
  • 캐논 5D 펌웨어 | Dslr 펌웨어 업그레이드 방법 82 개의 베스트 답변 on 캐논 EOS 30D 펌웨어 Ver 1.0.6 , EOS 5D 펌웨어 Ver 1.1.1
  • Top 5 캐논 5D 펌웨어 Top 89 Best Answers on 캐논 EOS 30D 펌웨어 Ver 1.0.6 , EOS 5D 펌웨어 Ver 1.1.1
  • 편리 on 워드프레스 애니메이션 gif 파일을 mp4로 변환하여 출력하기
  • 임팀장 on 워드프레스 애니메이션 gif 파일을 mp4로 변환하여 출력하기
  • 편리 on Notepad++ NppFTP 플러그인 수동 설치
  • paul-j on Notepad++ NppFTP 플러그인 수동 설치
  • YS on Windows 10 iCloud 사진 저장 폴더 변경
  • 편리 on Docker를 이용한 Centos7 + httpd + php 5.4 개발환경 구축

Meta

  • Log in
  • Entries feed
  • Comments feed
  • WordPress.org
© 2025 CHICPRO | Built using WordPress and SuperbThemes