首页 > 解决方案 > 使用 Python 从 csv 文件中拆分和保存文本块

问题描述

我想将 csv 文件的每一行拆分为多个文本块并将它们保存为单独的文本文件(它只有 1 列,每行包含一个文本块)。我的 items_split 函数在定义的文本块上工作得很好,但是当应用于 csv 文件时我得到了错误

"文件"untitled.py",第 25 行,在 items_split 中 idx = text_lines.index("ABC") + 1

ValueError:“ABC”不在列表中”

我使用的代码如下:

import re
import uuid

def items_split(file):
    data=file
    ## First, we want to remove all empty lines in the text files
    data = re.sub(r'\n\s*\n','\n',data,re.MULTILINE)
    data = re.sub(r'\n\s*\n','\n',data,re.MULTILINE)
    data = re.sub(r'\n\s*\n','\n',data,re.MULTILINE)
    data = re.sub(r'\n\s*\n','\n',data,re.MULTILINE)
    data = re.sub(r'\n\s*\n','\n',data,re.MULTILINE)
    data = re.sub(r'\n\s*\n','\n',data,re.MULTILINE)
    data = re.sub(r'\n\s*\n','\n',data,re.MULTILINE)
    data = re.sub(r'\n\s*\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, we split the text files into multiple files, each with a news item 

    current_file = None
    for line in data.split('\n'):

        # Set initial filename, 
        if current_file == None and line != '':
            current_file = str(uuid.uuid4()) + '.txt' #this will assign a random file name 
            #current_file = line + '.txt'

        # This is to handle the blank line after Brief
        if current_file == None:
            continue

        text_file = open(current_file, "a")
        text_file.write(line + "\n")
        text_file.close()

        # Reset filename if we have finished this section
        # which is idenfitied by:
        #    starts with Demographics - ^Demographics
        #    contains some random amount of text - .*
        #    ends with ) - )$
        if re.match(r'^Demographics:.*\)$', line) is not None:
            current_file = None


import csv
with open('Book1.csv', 'rb') as csvfile:
    spamreader = csv.reader(csvfile, delimiter=',')
    for row in spamreader:
        items_split(row)

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

“媒体新闻报道

美国广播公司

话题 1 dzfffa a agasgeaherhryyeshdh

人口统计数据:12,000(男性 16 岁以上) • 7,000 人(女性 16 岁以上)

话题二

fszg seez trbwtewtmytmutryrmujfcj

人口统计数据:10,000(男性 16 岁以上) • 5,000 人(女性 16 岁以上)

你对这个内容满意吗?"

我想把它分成:

美国广播公司

话题 1 dzfffa a agasgeaherhryyeshdh

人口统计数据:12,000(男性 16 岁以上) • 7,000 人(女性 16 岁以上)

话题二

fszg seez trbwtewtmytmutryrmujfcj

人口统计数据:10,000(男性 16 岁以上) • 5,000 人(女性 16 岁以上)

你对这个内容满意吗?"

并将每个保存为单独的文本文件。我已经在文本本身上运行了这个函数,它工作得很好。问题是当我在 csv 文件上运行它时,它不知道每一行都是一个文本块,我尝试将它转换为字符串等,但都是徒劳的。

标签: python

解决方案


Python 有一个很棒的库,用于导入和读取 CSV 文件。永远不要重新发明轮子

CSV Python 2.X

来自文档的一个简短示例,解释了如何从 CSV 文件中读取数据。

import csv
with open('eggs.csv', 'rb') as csvfile:
     spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
     for row in spamreader:
         print ', '.join(row)

CSV Python 3.x

这个模块的工作方式类似,只是现在它返回一个 OrderedDict[] 类型,这使得导航文件更容易一些。

 import csv
 with open('names.csv', newline='') as csvfile:
     reader = csv.DictReader(csvfile)
     for row in reader:
         print(row['first_name'], row['last_name'])

推荐阅读