IT

파이썬 CSV 문자열을 배열로

lottoking 2020. 6. 1. 08:11
반응형

파이썬 CSV 문자열을 배열로


CSV로 인코딩 된 문자열을 구문 분석하여 배열 또는 사전으로 변환하는 간단한 라이브러리 또는 함수를 아는 사람이 있습니까?

필자 가 보았던 모든 예제에서 문자열이 아닌 파일 경로를 사용하기 때문에 내장 된 csv 모듈을 원하지 않는다고 생각 합니다.


io.StringIO다음을 사용하여 문자열을 파일 객체로 변환 한 다음 csv모듈에 전달할 수 있습니다 .

from io import StringIO
import csv

scsv = """text,with,Polish,non-Latin,letters
1,2,3,4,5,6
a,b,c,d,e,f
gęś,zółty,wąż,idzie,wąską,dróżką,
"""

f = StringIO(scsv)
reader = csv.reader(f, delimiter=',')
for row in reader:
    print('\t'.join(row))

split()바꿈이있는 간단한 버전 :

reader = csv.reader(scsv.split('\n'), delimiter=',')
for row in reader:
    print('\t'.join(row))

또는 구분 기호 split()로 사용 하여이 문자열을 줄로 \n묶은 다음 split()각 줄을 값으로 사용할 수 있지만 인용을 알고 있어야하므로 csv모듈을 사용하는 것이 좋습니다.

파이썬 2 당신은 수입에이 StringIO같은

from StringIO import StringIO

대신에.


단순-csv 모듈도 목록과 함께 작동합니다.

>>> a=["1,2,3","4,5,6"]  # or a = "1,2,3\n4,5,6".split('\n')
>>> import csv
>>> x = csv.reader(a)
>>> list(x)
[['1', '2', '3'], ['4', '5', '6']]

>>> a = "1,2"
>>> a
'1,2'
>>> b = a.split(",")
>>> b
['1', '2']

CSV 파일을 구문 분석하려면 다음을 수행하십시오.

f = open(file.csv, "r")
lines = f.read().split("\n") # "\r\n" if needed

for line in lines:
    if line != "": # add other needed checks to skip titles
        cols = line.split(",")
        print cols

csv.reader() https://docs.python.org/2/library/csv.html 의 공식 문서 는 매우 유용합니다.

파일 객체와 목록 객체가 모두 적합합니다

import csv

text = """1,2,3
a,b,c
d,e,f"""

lines = text.splitlines()
reader = csv.reader(lines, delimiter=',')
for row in reader:
    print('\t'.join(row))

다른 사람들이 이미 지적했듯이 Python에는 CSV 파일을 읽고 쓰는 모듈이 포함되어 있습니다. 입력 문자가 ASCII 제한 내에 머무르는 한 꽤 잘 작동합니다. 다른 인코딩을 처리하려는 경우 더 많은 작업이 필요합니다.

csv로 모듈에 대한 파이썬 문서 구현 동일한 인터페이스를 사용하지만 문자열을 유니 코드 다른 인코딩 및 반품을 처리 할 수 csv.reader의 확장. 설명서에서 코드를 복사하여 붙여 넣기 만하면됩니다. 그 후 다음과 같이 CSV 파일을 처리 할 수 ​​있습니다.

with open("some.csv", "rb") as csvFile: 
    for row in UnicodeReader(csvFile, encoding="iso-8859-15"):
        print row

문서 :

모듈은 문자열 구문 분석을 직접 지원하지 않지만 쉽게 수행 할 수 있습니다.

import csv
for row in csv.reader(['one,two,three']):
    print row

Just turn your string into a single element list.

Importing StringIO seems a bit excessive to me when this example is explicitly in the docs.


https://docs.python.org/2/library/csv.html?highlight=csv#csv.reader

csvfile can be any object which supports the iterator protocol and returns a string each time its next() method is called

Thus, a StringIO.StringIO(), str.splitlines() or even a generator are all good.


Here's an alternative solution:

>>> import pyexcel as pe
>>> text="""1,2,3
... a,b,c
... d,e,f"""
>>> s = pe.load_from_memory('csv', text)
>>> s
Sheet Name: csv
+---+---+---+
| 1 | 2 | 3 |
+---+---+---+
| a | b | c |
+---+---+---+
| d | e | f |
+---+---+---+
>>> s.to_array()
[[u'1', u'2', u'3'], [u'a', u'b', u'c'], [u'd', u'e', u'f']]

Here's the documentation


Use this to have a csv loaded into a list

import csv

csvfile = open(myfile, 'r')
reader = csv.reader(csvfile, delimiter='\t')
my_list = list(reader)
print my_list
>>>[['1st_line', '0'],
    ['2nd_line', '0']]

Panda is quite powerful and smart library reading CSV in Python

A simple example here, I have example.zip file with four files in it.

EXAMPLE.zip
 -- example1.csv
 -- example1.txt
 -- example2.csv
 -- example2.txt

from zipfile import ZipFile
import pandas as pd


filepath = 'EXAMPLE.zip'
file_prefix = filepath[:-4].lower()

zipfile = ZipFile(filepath)
target_file = ''.join([file_prefix, '/', file_prefix, 1 , '.csv'])

df = pd.read_csv(zipfile.open(target_file))

print(df.head()) # print first five row of csv
print(df[COL_NAME]) # fetch the col_name data

Once you have data you can manipulate to play with a list or other formats.

참고URL : https://stackoverflow.com/questions/3305926/python-csv-string-to-array

반응형