简体   繁体   中英

Points for thousand mark and decimal mark

I have a messed up txt-file, with points as a thousand mark (1.000 or 19.329) and as a decimal mark (10000.3). Two example lines:

John;1.952;2003;20.365;1.214 

Ryan;2.342;2002;3045.3;345

I want to remove the point for the thousand mark and keep the points for the decimals. What is the easiest way to do this?

If you never have exactly three decimal places after the decimal point, the following will do it:

>>> import re
>>> re.sub(r"\.(\d\d\d(\D|$))", r"\1", "200.000.5")
'200000.5'

The regexp removes a dot if it is followed by exactly three digits. It won't match fewer digits (since it looks for three \\d ), and it won't match more since it looks for a non-digit after them ( \\D ).

Assuming that decimals are always only one digit:

line = "Ryan;2.342;2002;3045.3;345"
parts = line.split(";")

#Remove the name.
name = parts.pop(0) 

def fix(part):
    decimal = ""
    if part[-2] == '.':
        decimal = part[-2:]
        part = part[:-2]
    part = part.replace('.',',')
    return part+decimal

parts = [fix(part) for part in parts]
line = name+";"+";".join(parts)

I don't think there's a very easy way to do this.

That depends on the precision of your numbers. How many decimal places do the numbers in the text file have? If it's less than 3, then it should be trivial. If it's 3 or more, I'm not sure it can be done without at least some error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM