[英]How do I go about separating participants' data when it's all together?
[英]How to go about separating data in a .csv file?
我有一个.csv文件,其中包含一长串数据。 数据看起来类似于:
Name,Gender,Age John Smith,M,23 Ashley Jones,F,18 James Smith Johns,M,20
我的最终目标是分离所有数据,以便将它们放入行中。 我的预期结果将是:
['Name','Gender','Age','John Smith','M','23','Ashley Jones','F','18','James Smith Jones','M','20']
但是,使用类似:
line = line.split(",")
line = line.split(" ")
不会起作用,因为它将在或处将它们分开,并且会有类似以下的值:
'Age John Smith' or 'Age','John','Smith'
有什么办法可以解决此问题?
首先在处分割,
然后遍历该列表,并在空格处的每个项目处分割。 如果在空格处分割后返回的项目数大于1,则分别返回第一项和其余项,否则只需返回第一项即可。
import csv
def solve(row):
for item in row:
spl = item.split(None, 1)
if len(spl) > 1:
yield spl[0]
yield spl[1]
else:
yield spl[0]
...
with open('abc1') as f:
reader = csv.reader(f, delimiter=',')
for row in reader:
print list(solve(row))
...
['Name', 'Gender', 'Age', 'John Smith', 'M', '23', 'Ashley Jones', 'F', '18', 'James Smith Johns', 'M', '20']
这是使用正则表达式的解决方案:
re.compile("([^,]+),([^,]+),(\d+|Age)\s+").findall("Name,Gender,Age John Smith,M,23 Ashley Jones,F,18 James Smith Johns,M,20")
其结果将是:
[('Name', 'Gender', 'Age'), ('John Smith', 'M', '23'), ('Ashley Jones', 'F', '18')]
有很好的re
解决方案,但我只想添加此非正则表达式解决方案:
>>> s = "John Smith,M,23 Ashley Jones,F,18 James Smith Johns,M,20"
>>> sum((item.split(None, 1) for item in s.split(',')), list())
['Name', 'Gender', 'Age', 'John Smith', 'M', '23', 'Ashley Jones', 'F', '18', 'James Smith Johns', 'M', '20']
除了sum
,还可以使用itertools.chain
。 但是最后,它似乎一点都不短。
>>> list(itertools.chain(*[item.split(None, 1) for item in s.split(',')]))
或更好
>>> list(itertools.chain.from_iterable(item.split(None, 1) for item in s.split(',')))
正则表达式的方式。 :-)
>>> s = "John Smith,M,23 Ashley Jones,F,18 James Smith Johns,M,20" #Note: no title here.
>>> [(x.group(1), x.group(3), x.group(4)) for x in re.finditer(r"(\S+( \S+)),(\S),(\d+)",s)]
[('John Smith', 'M', '23'), ('Ashley Jones', 'F', '18'), ('Smith Johns', 'M', '20')]
请注意,我已经删除了标题(第一行),您需要相应地修改regexp或修改输入字符串。
正如我在示例中看到的,行将是line = line.split(",")
enoght。 也许我什么都没得到?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.