开发者

Parsing name and address information with differing number of spaces

开发者 https://www.devze.com 2022-12-17 23:55 出处:网络
I have a comma delimited text file. The 5th field on each line conta开发者_如何学Cins the name and address information. The name is separated from the street information by a \'¬\' character. The sam

I have a comma delimited text file. The 5th field on each line conta开发者_如何学Cins the name and address information. The name is separated from the street information by a '¬' character. The same character also separates the city|state|zip. A sample field would be:

"¬BOL¬MICKEY M MOUSE¬123 TOMORROW LANE¬ORLANDO FL 12345-6789¬¬¬¬EOL¬"

I need to separate the name into parts and the city|state|zip into parts. However, the name may or may not have a middle initial so:

m = l[4].split("¬")

firstName, mi, lastName = m[2].split()

won't work if there is no middle initial. Also, the name of the city may or may not have spaces so:

city, state, zipCode = m[4].split()

won't work if the city is 'San Antonio' or 'Rio de Janeiro' for instance.

Bottom line, how do I parse sections of a field where the section is not always in the same format?


In your examples it seems that you can in both cases solve the problem by getting the 'first fields', the 'last fields' and 'everything in between':

m = line.split("¬")[2].split()
firstname = m[0]
surname = m[-1]
initials = m[1:-1] # Maybe just keep this as a list?

And:

m = line.split("¬")[4].split()
city = ' '.join(m[:-2])
state = m[-2]
zipCode = m[-1]

In general you can handle a single field containing spaces by getting the 'fixed' fields from both the start and the end and whatever is left over is the field that can contain spaces.. As soon as you have two fields containing spaces in the same column, there's nothing you can do. It's ambiguously defined.

With the data format you have, you may have some problems if there are people with first or last names containing spaces such as Robert Van de Graff. This can be solved if you have an initial by looking for words containing only one letter such as: Robert J. Van de Graaff and using those to define where the first and last names start and end. But in general you may have problems.

Also there's an internationalization issue hidden here: not everyone writes their 'first name' first - sometimes they write their family name first.


Basically what Anon suggests, you can implement it like this:

cityInfo = m[4].split()
city, state, zipCode = ' '.join(cityInfo[:-2]), cityInfo[-2], cityInfo[-1])
0

精彩评论

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