我可以通过多种方式解决这个问题,但我想使用 Python。下面是问题:
我有一个 CSV 文件,其中包含如下值:
Name Address Skills
Napoleon Preston, Idaho Bowhunting, Computer Hacking, Drawing Unicorns
我想把它改成这样:
Name Address Skill
Napoleon Preston, Idaho Bowhunting
Napoleon Preston, Idaho Computer Hacking
Napoleon Preston, Idaho Drawing Unicorns
我已经研究过,并且已经阅读了 CSV 库,但我觉得我最终会做一些非常丑陋和过于复杂的事情。
最佳答案
现在您有了一个平面文件,我相信操作数据的第一步是将它加载到 Python 中,这样您就可以开始使用它了。
您走在正确的轨道上。 csv 模块就是为此设计的
假设您的数据是制表符分隔的
import csv
with open('your_csv.csv') as f:
f.readline() # these are headings should remove them
csv_reader = csv.reader(f, delimiter='\t')
for line_list in csv_reader:
# line_list is a list of each row of your csv
# line_list[0] Contains 'Name' data 'Napolean'
# line_list[1] Cotinas Address 'Preston, Idaho'
# line_list[2] Contains skills 'Bowhunting, Computer Hacking, Drawing Unicorns'
skills_list = [x.strip() for x in line_list[2].split(',')]
for skill in skills_list:
#line_list[0] line_list[1], skill
Napoleon Preston, Idaho Bowhunting
Napoleon Preston, Idaho Computer Hacking
Napoleon Preston, Idaho Drawing Unicorns
关于python - 将分隔的字符串/单元格值拆分为多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12974866/