A little Python string manipulation help...

Status
Not open for further replies.
So I have a data dump that's supposed to represent a person's height. The data is crap and I'm trying to clean it up. Ultimately, I aim to have a separates fields for feet and inches.

Here's what the data looks like now:
Code:
5’8”
5’10”
5'8
5'11''
5'7
5'11
6'
5'7''
5'10"

Absolutely no validation when people were entering data. My plan is to parse out the first number, feet, and then grab the inches. I've been looking at the data in Python:
Code:
import csv
reader = csv.reader(open('Height.csv', "rb"), delimiter = ',')
for row in reader:
	print row

The problem is if the string has no spaces as in 5'8", Python reads it as:
Code:
5\xe2\x80\x998\xe2\x80\x9d

I think it's because of the quotes but I cannot figure out how to solve this.

Any ideas?
 

Grayrest

Ars Tribunus Militum
2,499
I assume you're actually reading in a CSV file otherwise it's easier to just open('file.txt').readlines() in your for loop. You also might want to set the quotechar to something weird so the CSV reader doesn't try to interpret your quotes:
Code:
import csv
reader = csv.reader(open('Height.csv', "rb"), delimiter = ',', quotechar='|')
for row in reader:
   print row
As for your output, it's just the Python repl's way of printing non-ascii characters. In this case, your input was typographic quotes and if you print it, you should see the typographic quotes in the terminal:
Code:
>>> a = '5\xe2\x80\x998\xe2\x80\x9d'
>>> print '5\xe2\x80\x998\xe2\x80\x9d'
5’8”
If you're having trouble matching it, convert to straight quotes:
Code:
>>> a.replace('\xe2\x80\x99',"'").replace('\xe2\x80\x9d','"')
'5\'8"'
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
I'd be somewhat averse to having separate fields for feet and inches.

Instead store in a decimal form and convert to the relevant display format as needed (you will find this helps if down the line people want to use meters/centimeters).

Don't force your display model onto your data model. The value you are storing is 'height_in_feet'. Compare that to: 'height_in_round_feet_rounded_down', 'height_excess_in_inches' which is the original. It is much easier to work with one and not the other.
 
ShuggyCoUk":3ux7rjiq said:
I'd be somewhat averse to having separate fields for feet and inches.

Instead store in a decimal form and convert to the relevant display format as needed (you will find this helps if down the line people want to use meters/centimeters).

Don't force your display model onto your data model. The value you are storing is 'height_in_feet'. Compare that to: 'height_in_round_feet_rounded_down', 'height_excess_in_inches' which is the original. It is much easier to work with one and not the other.

This is good advice. So in other words, what you are suggesting is if the UI has select box for feet and select box for inches, write a method that converts them to decimal and store that value in the db. Is that right?
 
LordHunter317":1ctamczu said:
Unless someone said they were 5'7.5"
It depends on the requirements, which the OP didn't state completely. Given the limited sample that the OP provided, just storing whole inches may be suitable. For more precision, you might want to store inches * 10 as an integer or inches as a float.
 
If anyone is interested, I have solved my problem. Basically my CSV file had two columns, one for the unique ID and one for the height. I was able to put a '*' after the feet value in order to separate the feet from inches. From there, I ran the following code to parse out the ID, feet and inches. While the code is crude and doesn't have error handling, it did the job. I'm sure that the experts here on ars would do this a lot more elegantly than I did.

Thanks to all for your help!

Code:
import string
file = open('Height.csv')
for line in file.readlines():
        line = line.split(',')
        ID = line[0]
        TotalHeight = line[1]
        TotalHeight = TotalHeight.strip()
        Feet = TotalHeight[0]
        Feet = Feet.strip()
        if TotalHeight == 'NULL':
                TotalHeight = 'NULL'
                
        else:
                TotalHeight = TotalHeight.split('*')
                inches = TotalHeight[1]
                inches = inches.strip()
        if Feet == 'N':
              Feet = ''
              
        if Feet == '':
                inches = ''
                
        print ID + ', ' + Feet + ', ' + inches
 

bk0

Ars Tribunus Militum
1,801
I've had to do this also, though my data was far worse. I had a random assortment of things like:

6'
5ft 3"
4 foot eleven
57 [apparently intended to mean 5ft7in]
five feet

...etc. I ended up calculating inches by hand for each observation and learned my lesson about data input validation.

The original question was about Python, but if you use R you can calculate inches without having to loop:
Code:
> heightdf <- read.csv("height.csv")
> heightdf
  height
1  5'11"
2   5'7"
3   5'9"
4   6'1"
5   5'1"
6   5'3"
7   5'3"
8  4'11"
9   5'1"
> h_mat <- matrix(as.integer(unlist(strsplit(as.character(heightdf$height), "[',\"]"))), length(heightdf$height), 2, byrow = TRUE)
> h_mat
      [,1] [,2]
 [1,]    5   11
 [2,]    5    7
 [3,]    5    9
 [4,]    6    1
 [5,]    5    1
 [6,]    5    3
 [7,]    5    3
 [8,]    4   11
 [9,]    5    1
> hdf <- data.frame(h_mat)
> hdf
  X1 X2
1  5 11
2  5  7
3  5  9
4  6  1
5  5  1
6  5  3
7  5  3
8  4 11
9  5  1
> h_inches <- (hdf$X1*12)+hdf$X2
> hdf <- data.frame(hdf, h_inches)
> names(hdf) <- c("orig_feet", "orig_inches", "total_height_inches")
> hdf
  orig_feet orig_inches total_height_inches
1         5          11                  71
2         5           7                  67
3         5           9                  69
4         6           1                  73
5         5           1                  61
6         5           3                  63
7         5           3                  63
8         4          11                  59
9         5           1                  61
> write.csv(hdf, "height2.csv")

Obviously this doesn't do any error checking or validation, but you get the idea.
 
bk0":2ibsat3n said:
I've had to do this also, though my data was far worse. I had a random assortment of things like:
6'
5ft 3"
4 foot eleven
57 [apparently intended to mean 5ft7in]
five feet

Isn't it funny. My source data came from a hack FileMaker Pro database. The project has posed a challenge for me. I'm definitely learning a lot about string manipulation and the power of Python.


I went ahead and converted my height field to inches. On the front end, the user chooses from combo boxes, feet and inches. I wrote a php function that converts feet and inches to inches to send to the database and I wrote a function that converts inches to feet and inches to display the height on the page. This allows me to do a direct comparison (inches to inches) when the user is searching for people between a range of heights.
 
Status
Not open for further replies.