Note that there are some explanatory texts on larger screens.

plurals
  1. POPython makes four digit string into int implicitly
    text
    copied!<p>I'm currently working on a script which extracts data from two sources where one of those is Norwegian post codes. Norwegian post codes are made up of four digits and some begins with a zero. </p> <p>Here is the code: </p> <pre><code>#This section loads data on Norwegian post codes and places into a dictionary where postcode is key f = open("postoversikt.txt", "r"); f1 = open("PCODES_USER_TRIM.txt","r") #load the file with all the users. fo = open("pcodes_out","w") place = {} times = {} for line in f: words = line.rsplit("\t"); place[str(words[0])] = words[1]; #Reverse these to change the key and value - Default key: postcode value: place number = 0; number_unique = 0; number_alike = 0; for line in f1: number = number + 1; words1 = line.rsplit(";"); if not words1[1] in times: number_unique = number_unique + 1; times[words1[1]] = 1; else: number_alike = number_alike + 1; times[words1[1]] = times[words1[1]] + 1; for key, value in times.items(): print key+";"+value+";"+words[key]; fo.write(key+";"+value+";"+words[key]+"\n"); print "Totalt antall objekter behandlet er: "+ str(number); print "Hvorav antall unike var: "+ str(number_unique); print "Antall like nummer ble funnet: " + str(number_alike); </code></pre> <p>Some lines from PCODES_USER_TRIM: </p> <pre><code>75621;4517;45 - 65 35214;7650;25 - 45 55624;9015;25 - 45 09523;5306;45 - 65 09051;2742;25 - 45 88941;1661;18 - 25 </code></pre> <p>Some lines from postoversikt.txt: </p> <pre><code>0001 OSLO 0301 OSLO P 0010 OSLO 0301 OSLO B 0015 OSLO 0301 OSLO K 0016 OSLO 0301 OSLO K 0017 OSLO 0301 OSLO K 0018 OSLO 0301 OSLO G 0021 OSLO 0301 OSLO K 0022 OSLO 0301 OSLO K </code></pre> <p>One of the problems that occur is that the postcodes that begins with a zero is striped of the initial zero. My guess is that this is due to an internal conversion to an int (I'm just a beginner in Python, so please forgive if my problems are a bit mundane). I would like these to be in the standard format of four numbers xxxx. My second problems which I guess follows from my first is that I want to add the name of the post code to the final print out. This doesn't work as I can't use the key to refer to the place in words. </p> <p>I used to convert the object I print to Strings using the str() method, but I refrained from doing so in the current version as I want to handle the problem by its root. </p> <p>Could someone please help me with my little problem? How could I use rsplit to put Strings into the words dictionary without converting it to integers? </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload