首页 > 编程知识 正文

python字符串拆分为单个字符,python处理大容量csv数据

时间:2023-05-05 14:08:30 阅读:165295 作者:1100

您希望将csv文件中的每一行拆分为多个文本块,并将它们另存为单独的文本文件。 一列包含一个文本块。 我的items_split函数与定义的文本块完全相同,但应用于csv文件时收到了错误

“File “untitled.py”,line 25,in items_split

idx=text_lines.index(「ABC”) 1

value error :‘ABC’is notinlist "

我使用的代码如下。

导入re

导入uuid

efitems_split(file ) :

data=文件

## First,wewanttoremoveallemptylinesinthetextfiles

DATA=re.sub(r'ns*n ','n ',data,re.MULTILINE ) )。

DATA=re.sub(r'ns*n ','n ',data,re.MULTILINE ) )。

DATA=re.sub(r'ns*n ','n ',data,re.MULTILINE ) )。

DATA=re.sub(r'ns*n ','n ',data,re.MULTILINE ) )。

DATA=re.sub(r'ns*n ','n ',data,re.MULTILINE ) )。

DATA=re.sub(r'ns*n ','n ',data,re.MULTILINE ) )。

DATA=re.sub(r'ns*n ','n ',data,re.MULTILINE ) )。

DATA=re.sub(r'ns*n ','n ',data,re.MULTILINE ) )。

## Then,we remove all lines up to ABC

text_lines=data.split('n ' ) )。

idx=text_lines.index('ABC ' ) 1

data='n '.join (text _ lines [ idx : ] ) ) ) ) ) ) )。

## Last,wesplitthetextfilesintomultiplefiles,each with a news item

current_file=None

forlineindata.split('n”) :

# Set initial filename,

if current_file==None and line!='':

current_file=str(uuid.uuid4() ).txt ) #thiswillassignarandomfilename

#current_file=line '.txt '

# thisistohandletheblanklineafterbrief

if current_file==None:

continue

text_file=open(current_file,' a ' ) )。

text_file.write(line'n ' ) )。

text_file.close (

# resetfilenameifwehavefinishedthissection

# which is idenfitied by:

# starts with demographics-^ demographics

# containssomerandomamountoftext--.*

#endswith(-) $

ifre.match (r (^ demographics :*) $ )、line ) is not None:

current_file=None

import csv

withopen(book1.CSV,) rb ) as csvfile:

SPAMreader=CSV.reader(CSVfile,delimiter=',')

for row in spamreader:

items_split(row )

例如,csv文件中的每一行可能如下所示:

“媒体新报告

哥伦比亚广播公司

topic1dzfffaagasgeaherhryyeshdh

demographics :12,000 (male 16 ) 7000 (female 16 )

Topic 2

fszgseeztrbwtewtmytmutryrmujfcj

demographics :10,000 (male 16 ) 5000 (female 16 )

Are you happy with this content? 「

我想把它分开:

哥伦比亚广播公司

topic1dzfffaagasgeaherhryyeshdh

demographics :12,000 (male 16 ) 7000 (female 16 )

Topic 2

fszgseeztrbwtewtmytmutryrmujfcj

demographics :10,000 (male 16 ) 5000 (female 16 )

Are you happy with this content? 「

将每个文件另存为单独的文本文件。 我已经在文本本身上执行了这个功能,那是完全正常的。 问题是,在csv文件中运行时,不知道每行都是文本块,尝试转换为字符串是徒劳的。

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。