python - 在python中按索引访问单词
问题描述
我不知道这是否可能,但我正在尝试通过索引从拆分字符串中访问单词(不是单个字符)并将其存储在字典中。如果这不起作用,请就如何获得相同的结果提出任何其他建议。到目前为止,这是我的代码:
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
解决方案
如果单词之间有逗号,那么您可以执行words = i.split(',')
或将分隔符作为参数传递给split()
推荐阅读
- c++ - 将非静态类成员回调函数传递给 ros::subscriber
- excel - 在 Excel 宏的 Powerpoint 中显示 MsgBox
- ios - 自定义 UIButton 没有点击效果
- java - 如何使用 ModelMapper (Spring Boot) 将嵌套对象映射到嵌套 DTO
- javascript - 如何检查字符串的字符是否已经是数组的元素?
- php - 使用 Laravel 优化从数据库中已存在的数组中删除值
- azure-devops - Azure DevOps 使用 oAuth 令牌完成 PR
- algorithm - 确定一个值是否在多个范围内的有效方法
- c# - 如何在 C# 中使用 foreach 循环更改其范围
- spring - 邮递员多部分/表单数据在春季不起作用