开发者

parsing out a second delimited data structure

I am reading in a .csv file similar to the following. Note that PhoneNumbers can contain multiple values delimited by the pipe character.

FirstName,LastName,PhoneNumbers

Bucky,Fuller,213.283.5555|714.345.5566

Stephen,Hawking,212.456.7897|312.345.6677|415.223.3423

Robert,Heinlein,562.457.8899

I am able to read in the .csv file and write out to a file using the following.

.....
dReader = csv.DictReader(open('employee_import.csv', 'rb'), delimiter=',', quotechar='`')
for row in dReader:
file.write("\t\t\t<PHONEBOOK>\n")
file.write("\t\t\t\t<LASTNAME>"+str(row.get('LastName'))+"</LASTNAME>\n")
file.write("\t\t\t\t<FIRSTNAME>"+str(row.get('FirstName'))+"</FIRSTNAME>\n")
file.write("\t\t\t\t<PHONENUM>"+str(row.get('PhoneNumbers'))+"</PHONENUM>\n")
    file.write("\t\t\t<PHONEBOOK>\n")
.....

I was wondering if anyone had any ideas how I could iterate through the PhoneNumbers Key,Value pair so that I can separate out the m开发者_如何学运维ultiple PhoneNumbers a person can have? Thank you.


Why not split the phone number field?

for number in str(row.get('PhoneNumbers')).split('|'):
  file.write("\t\t\t\t<PHONENUM>"+number+"</PHONENUM>\n")


I haven't tested this, but I think it ought to take a string, chop it up into substrings based on the '|' delimiter, and return a list of such strings. Hope it helps.

def parser(string):
phone_numbers = []
i = ''
for character in string:
    if character != '|':
        i+=character
    else:
        phone_numbers.append(i)
        i = ''
        continue
return phone_numbers
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜