python - 在 Python 中组织数据集
问题描述
我有一个包含大量习语的 .csv 数据集。每行包含我想分隔的三个元素(用逗号分隔):
1) 索引号 (0,1,2,3...)
2) 成语本身
3)如果成语是肯定的/否定的/中性的
这是 .csv 文件的一个小示例:
0,"I did touch them one time you see but of course there was nothing doing, he wanted me.",neutral
1,We find that choice theorists admit that they introduce a style of moral paternalism at odds with liberal values.,neutral
2,"Well, here I am with an olive branch.",positive
3,"Its rudder and fin were both knocked out, and a four-foot-long gash in the shell meant even repairs on the bank were out of the question.",negative
如您所见,有时成语会包含引号,而有时则不会。但是,我认为这不会很难排序。
我认为在 Python 中组织它的最佳方法是通过字典,如下所示:
example_dict = {0: ['This is an idiom.', 'neutral']}
那么如何将每一行分成三个不同的字符串(基于逗号),然后使用第一个字符串作为键号,最后两个作为字典中的相应列表项?
我最初的想法是尝试用这段代码分割逗号:
for line in file:
new_item = ','.join(line.split(',')[1:])
但它所做的只是删除一行中第一个逗号之前的所有内容,而且我认为通过它进行大量迭代并不是有效的。
我想就组织这样的数据的最佳方法获得一些建议?
解决方案
Python 有一个专门用于处理文件的完整模块。csv
在这种情况下,您可以使用它从文件中创建列表列表。现在让我们调用您的文件idioms.csv
:
import csv
with open('idioms.csv', newline='') as idioms_file:
reader = csv.reader(idioms_file, delimiter=',', quotechar='"')
idioms_list = [line for line in reader]
# Now you have a list that looks like this:
# [[0, "I did touch them...", "neutral"],
# [1, "We find that choice...", "neutral"],
# ...
# ]
您现在可以对数据进行排序或按您喜欢的方式组织数据。
推荐阅读
- apache-nifi - 调试复杂 NiFi 数据流的理想方法
- spring - 在 Spring Boot 中禁用 /cloudfoundryapplication
- powershell - Powershell 复制文件,将源路径、搜索字符串和目标路径作为参数传递
- go - 是否可以将 Go 程序编译为 LLVM IR?
- ios - 是否必须转换为 Swift 4?即使不是强制性的,我也应该转换吗?
- java - 是否可以将 Mockito 中的某些返回值列入黑名单?
- python - 为什么 MATLAB 的 svd 比 Python 快得多?
- php - 我将如何遍历此 API 数据
- javascript - 脚本适用于 Adobe Dreamweaver Preview,但不适用于 Chrome 和 Edge
- python - 如何解决“valueError:无法将 DataFrame 与类型的实例合并”
“?