【发布时间】: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