파이썬에서 데이터 읽기

jigu의 이미지

안녕하세요. 포트란을 쓰다가 파이썬으로 갈아탈려고 공부 중입니다.

제가 쓰는 부분은 데이터 읽고 계산하고 쓰고 그게 다 입니다.

데이터 개수가 좀 많은 것 빼고는 구구단에 가까운 상황인데, 읽는 걸 잘 못해서요.

우선 파일을 열고 라인으로 읽고 쓰는 건 문제가 없는 상황입니다.

세 가지 형태의 데이터 읽기 질문을 드리고 싶습니다.

(질문1) m x n 의 데이터가 있고 m, n을 아는 경우

data.txt
3 4
0.0 0.12 0.4 0.70
1.02 0.00 0.01 0.02
2.0 1.12 1.3 1.7

이런 데이터를 A(4,3)짜리 배열에 넣고 싶습니다.

포트란에서는

read( 10, * ) m, n
do i = 1, m
  read( 10, * ) (A(i,j),j=1,n)
enddo

이렇게 쓰며 되는데 파이썬에선 라인으로만 읽어서 어떻게 해야하는 지 모르겠습니다...

lines = file1.readlines()
for line in lines:
  file2.write(line)
  dum1, dum2, dum3, dum4 = line.split()

이렇게 해서 나누긴 하겠는데 array로 넣을려면 어떻게 해야할 지 모르겠습니다.

n이 늘어나면 저걸 다 쓸 수도 없구요..

(질문2)그리고 위와 동일한 상황에서 m을 모를 때는 어떻게 해야할 지 궁금합니다.

 
lines = file1.readlines()
m = len(lines)


이렇게 쓰니까 m에 들어가던데 맞는 방법인지 모르겠네요.

(질문3)마지막으로 데이터를 읽다가 일정 패턴이 보이면 데이터를 읽는 방법입니다.

...
...
...
abc Num 1 1.0 2.0 3.0
...
abcd Num 2 2.0 3.0 4.0
...
d Num 3 1.0 2.0 3.0
...
...

두 번 째 칸의 데이터가 Num이면 그 줄의 데이터를 뽑아서 배열에
1.0 2.0 3.0
2.0 3.0 4.0
이렇게 넣고 싶은데 어떻게 하면 좋을 지 질문드립니다.

shint의 이미지

만드는데. 3시간이 넘게 걸리네요. ㅇ_ㅇ;;
별로 필요없는 내용이지만.
만들면서 참고한 내용을 같이 첨부합니다.

여기서 바로 테스트하실 수 있습니다.
https://www.python.org/

http://www.thegeekstuff.com/2013/08/python-array/

https://docs.python.org/3/tutorial/introduction.html#strings
https://docs.python.org/2/tutorial/introduction.html
https://docs.python.org/2.3/whatsnew/section-slices.html

#//----------
#//flat 형 출력하기 성공
#//----------
from array import *
 
from array import *
my_array = array('f', [1.1,2.2,3.3,4.4,5.5])
for f in my_array:
print(f)
 
my_array2 = array('f', [1.1,2.2,3.3,4.4,5.5])
for i in my_array2:
print(i)
 
 
 
#//----------
#//float 형 분리하기 성공
#//----------
ar_float = array('f', [0.0, 0.12, 0.4, 0.70, 1.02, 0.00, 0.01, 0.02, 2.0, 1.12, 1.3, 1.7])
print(ar_float[0],ar_float[1],ar_float[2])
print(ar_float[3],ar_float[4],ar_float[5])
print(ar_float[6],ar_float[7],ar_float[8])
print(ar_float[9],ar_float[10],ar_float[11])
 
 
 
#//----------
#//문자열 분리하기 성공
#//----------
byte = "0.0 0.12 0.4 0.70 1.02 0.00 0.01 0.02 2.0 1.12 1.3 1.7"
ar = byte.split(" ")
for i in ar:
    print(i)
 
 
#//----------
#//파일 저장하기
#//----------
f = open('data.txt', 'w')
f.write("0.0 0.12 0.4 0.70\n")
f.write('1.02 0.00 0.01 0.02\n')
f.write('2.0 1.12 1.3 1.7\n')
f.close()
 
 
#//----------
#//파일 읽기
#//----------
f = open('data.txt', 'rt')
#print (f.readline())
#print (f.read())
 
byte1 = f.readline()
ar1 = byte1.split(" ")
 
byte2 = f.readline()
ar2 = byte2.split(" ")
 
byte3 = f.readline()
ar3 = byte3.split(" ")
 
f.close()
 
tmp = ar1[len(ar1)-1].split("\n")
ar1[len(ar1)-1] = tmp[0];
 
tmp = ar2[len(ar2)-1].split("\n")
ar2[len(ar2)-1] = tmp[0];
 
tmp = ar3[len(ar3)-1].split("\n")
ar3[len(ar3)-1] = tmp[0];
 
print (ar1)
print (ar2)
print (ar3)
 
print (ar1[0],ar2[0],ar3[0])
print (ar1[1],ar2[0],ar3[0])
print (ar1[2],ar2[0],ar3[0])
print (ar1[3],ar2[0],ar3[0])

댓글 첨부 파일: 
첨부파일 크기
Plain text icon 문서.txt7.74 KB

----------------------------------------------------------------------------
젊음'은 모든것을 가능하게 만든다.

매일 1억명이 사용하는 프로그램을 함께 만들어보고 싶습니다.
정규 근로 시간을 지키는. 야근 없는 회사와 거래합니다.

각 분야별. 좋은 책'이나 사이트' 블로그' 링크 소개 받습니다. shintx@naver.com

jigu의 이미지

처음이라 그런 지 다 어렵게 느껴지네요.
알려주신 링크 타고 공부 좀 더 해야겠습니다.
감사합니다.

jick의 이미지

파이썬은 기본적으로 제공하는 타입에 array가 없고 그 대신 list로 거의 모든 것을 해결합니다.

list의 장점이라면 만들 때 미리 사이즈를 지정해줄 필요가 없다는 것이죠. 그냥 빈 리스트(= [])를 만들고 한줄씩 추가하면 됩니다.

http://stackoverflow.com/questions/3277503/python-read-file-line-by-line-into-array

data = []
with open('filename') as f:
    for line in f:
        data.append(line.split())
        # 혹은 다음과 같이:
        items = line.split()
        if items[1] == 'Num':
            data.append(items[2:])
jigu의 이미지

input파일이 아래와 같은 상황에서

a 1 3
b 2 3
c 3 3

import sys
filea = sys.argv[1]
file1 = open(filea, 'r')
data = []
for line in file1:
  items=line.split()
  data.append((items[1:])
 
for i in range(3):
  print( data[i][0]*data[i][1] )


1 3
2 3
3 3
을 data에 넣었는데 이걸 float로 바꿀려고 for 문 위에

data1=map(float, data)

data1=list(map(float, data))

이렇게 해봤는데 TypeError: float() argument must be a string or a number, not 'list' 라고 뜨네요.

float으로만 바꾸면 data[i][j]로 뽑아 쓰면 될 것 같은데 방법이 없을까요?

Python 3.0입니다.

lucidite의 이미지

적어주신 코드대로 하시면, data는 str을 원소로 하는 list의 list가 됩니다.
위와 같이 map 함수를 사용하면 list에 float 함수를 적용하는 게 되므로 TypeError가 나겠지요.
쉽게 처리하자면 바깥쪽에 for-loop를 하나 더 돌릴 수도 있을 것이고...적어주신 코드에 리스트 내포를 사용하면:
data = [(map(float, d)) for d in data]
와 같이 처리할 수 있겠네요.

그 외에도 방법은 여러 가지 있을 것이고, 파일에서 읽어오시는 거라면 표준 라이브러리에서는 csv 모듈을 사용할 수도...

[/]
jigu의 이미지

감사합니다. csv 모듈을 공부해보겠습니다~

lucidite의 이미지

list가 글에서 나타나지 않네요. 자주 안 쓰다보니 잘 몰라서..^^;
data = [ list (map(float, d)) for d in data] 와 같이 해야 합니다. 안 그러면 map 객체의 list가 되어서...
사용하시려는 용도로는 위의 코드 정도로도 충분할 것 같습니다. csv를 사용하실 경우 csv.genfromtxt 등의 함수를 쓰시면 될 겁니다.

jigu의 이미지

말씀하신 대로 작성했는데... 에러가 나오네요..

for i in range(80) :
  items = file1.readline().split()
  if items[0] == 'Spec' : break
Spec = items[4:]
print( Spec )

위처럼 하면 Spec이 문자로 잘 나오는데,

Spec부분을 float으로 만드는 건 여전히 안되네요..

Spec = [ list( map( float, d ) ) for d in items[4:] ]

에러 메시지는 ValueError: could not convert string to float: '.' 입니다.

혹시 해결방법이 있을까요?

lucidite의 이미지

위에서는 데이터가 2차원이니 2중으로 작성한 것이었고..
(리스트 내포, map이 중첩되어 2중 순회가 됩니다. 문장으로는 한 줄이지만..)
위에 쓰신 코드에서는 items가 문자열의 1차원 리스트니까,
Spec= list (map (float, items[4:]))로 충분합니다.
아니면 Spec= [float(s) for s in items[4:] ] 까지만..
(2중 순회를 하면 문자열을 순회하면서 0.1을 0, ., 1로 순회하는데 여기서 소숫점을 float 변환하면서 문제가 발생합니다. 물론, 애초에 원하던 결과도 아닐 것이고요.)

jigu의 이미지

현재까지 매우 잘 읽고 float로 변환도 잘 하네요 ^^

lucidite의 이미지

genfromtxt는 제 실수입니다. csv 모듈의 함수가 아니라 아래 다른 분이 언급해주신 numpy 모듈에서 사용하는 함수일 겁니다. csv 모듈을 사용할 경우 방식이 좀 다릅니다.요즘 고수준 데이터 처리 라이브러리만 쓰다보니 착각했네요. 혼선을 드려 죄송합니다 ;)

qiiiiiiiip의 이미지

포트란 대신 사용할 목적이라면, numpy 를 이용해보심이..

> import numpy
> a=numpy.loadtxt('input',usecols=[1,2])
> a
array([[ 1.,  3.],
       [ 2.,  3.],
       [ 3.,  3.]])
>
jigu의 이미지

지금은 간단하게 읽고 비교하고 더하고 빼고만해서 모르겠지만

쓰다보면 복잡한 계산도 더 해야할 것 같아서 numpy 도 공부해야겠습니다.

지금은 더하기 빼기도 어렵네요;

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.