【发布时间】:2020-07-13 23:31:14
【问题描述】:
我不知道这是否可能,但我正在尝试通过索引从拆分字符串中访问单词(不是单个字符)并将其存储在字典中。如果这不起作用,请就如何获得相同的结果提出任何其他建议。到目前为止,这是我的代码:
def main():
if len(argv) != 2:
print("usage: python import.py (csv file)")
exit(0)
db = SQL("sqlite:///students.db")
file = open(argv[2], 'r')
csv_file = DictReader(file)
for row in csv_file:
names = row['name']
for i in names:
word = i.split()
# what the csv looks like
name,house,birth
Adelaide Murton,Slytherin,1982
Adrian Pucey,Slytherin,1977
Anthony Goldstein,Ravenclaw,1980
# what i want it to look like
first name,middle name,last name,house,birth
Adelaide,None,Murton,Slytherin,1982
Adrian,None,Pucey,Slytherin,1977
Anthony,None,Goldstein,Ravenclaw,1980
【问题讨论】:
-
如果您提供一些上下文(例如 CSV 的结构和最终数据结构的样例)会有所帮助。您是否希望通过表示包含特定键的 CSV 行列表的单词和值来保存字典?如果是这种情况,您可以枚举数据,并使用 setdefault 将单词添加为键(如果它尚不存在)并附加生成器中的当前索引。我们可以为您提供更多背景信息。 :)
-
我更新了代码以显示 csv 文件的结构以及我希望它之后的样子