python - 使用 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 有一个很棒的库,用于导入和读取 CSV 文件。永远不要重新发明轮子
来自文档的一个简短示例,解释了如何从 CSV 文件中读取数据。
import csv
with open('eggs.csv', 'rb') as csvfile:
spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
for row in spamreader:
print ', '.join(row)
这个模块的工作方式类似,只是现在它返回一个 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'])
推荐阅读
- c++ - 将 GLFW 静态链接到 CMake 到可执行文件
- sql-server - 如何在我的本地机器上设置数据库/服务器以测试和学习 Web 开发
- javascript - 有没有办法随机化 CSS/JavaScript 中的填充?
- mule - 如何在 Mule 4 中通过 ActiveMQ 传递属性
- php - Laravel 8 的问题:在 null 上调用成员函数 count()
- uml - 我如何设计一个演员不相互干扰的序列图?
- python - PyMongo 使用 docker 进行身份验证
- ubuntu - gtkterm 错误:启动 gtkterm 时出现远程登录被拒绝连接的错误
- python - 您可以使用 3 个单独的 1D numpy 数组来使用矢量化来操作 3D 数组吗?
- python-imaging-library - 我已经安装了枕头,但无法将其导入 python shell