【问题标题】:Split and save blocks of text from csv file with Python使用 Python 从 csv 文件中拆分和保存文本块
【发布时间】:2019-06-18 16:54:24
【问题描述】:

我想将 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 文件中的每一行如下所示:

“媒体新闻报道

ABC

主题 1 dzfffa agasgeaherhryyeshdh

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

主题 2

fszg seez trbwtewtmytmutryrmujfcj

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

您对此内容满意吗? "

我想把它拆分成:

ABC

主题 1 dzfffa agasgeaherhryyeshdh

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

主题 2

fszg seez trbwtewtmytmutryrmujfcj

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

您对此内容满意吗? "

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

【问题讨论】:

  • CSV(逗号分隔值)。您的文件可能具有 csv 扩展名,但它实际上不是 CSV,因为它没有逗号作为分隔符。尝试使用 csv 库时,这将导致未定义的行为。

标签: python


【解决方案1】:

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'])

【讨论】:

    【解决方案2】:

    您将 csv 中的一行(仅从一行文本中获得的列列表)传递给您的 item_split 函数,该函数需要一个以换行符分隔的字符串,因此该函数当然不能找到您期望的任何东西。

    由于您显然已经知道每个文本块的主题名称,因此您可以改用 re.split 按已知主题名称模式拆分您的 csv:

    import re
    import uuid
    with open('Book1.csv', 'r') as f:
        texts = iter(re.split(r'^(ABC|Topic 2)$', f.read(), flags=re.MULTILINE)[1:])
    for text in zip(texts, texts):
        with open(str(uuid.uuid4()) + '.txt', 'w') as f:
            f.write(''.join(text))
    

    这样第一个文件就会有:

    ABC
    
    Topic 1 dzfffa a agasgeaherhryyeshdh
    
    Demographics: 12,000 (male 16+) • 7,000 (female 16+)
    

    第二个文件将有:

    Topic 2
    
    fszg seez trbwtewtmytmutryrmujfcj
    
    Demographics: 10,000 (male 16+) • 5,000 (female 16+)
    
    Are you happy with this content?
    

    【讨论】:

      猜你喜欢
      • 2021-01-12
      • 1970-01-01
      • 2018-09-14
      • 1970-01-01
      • 2021-05-21
      • 1970-01-01
      • 2015-01-29
      • 1970-01-01
      • 2022-01-14
      相关资源
      最近更新 更多