I am new to python and have a hopefully simple question. I have a txt file with road names and lengths. i.e. Main street 56 miles. I am stumped on how to call on that file in Python and sort all the road lengths in ascending order. Thanks for your help.
Asked
Active
Viewed 134 times
-6
-
Dupe http://stackoverflow.com/questions/25690851/python-sorting-in-ascending-order-in-a-txt-file – therealprashant May 31 '15 at 18:57
-
https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files, https://docs.python.org/3/library/functions.html#sorted – MattDMo May 31 '15 at 19:00
-
possible duplicate of [Sort a Python dictionary by value](http://stackoverflow.com/questions/613183/sort-a-python-dictionary-by-value) – ScaisEdge May 31 '15 at 19:07
1 Answers
0
Let's assume that there is a "miles" after every number. (This is an untested code so you can get it edited but I think the idea is right).
EDIT: THIS IS TESTED
import collections
originaldict = {}
newdict = collections.OrderedDict()
def isnum(string):
try:
if string is ".":
return True
float(string)
return True
except Exception:
return False
for line in open(input_file, "r"):
string = line[:line.find("miles") - 1]
print string
curnum = ""
for c in reversed(string):
if not isnum(c):
break
curnum = c + curnum
originaldict[float(curnum)] = []
originaldict[float(curnum)].append(line)
for num in sorted(originaldict.iterkeys()):
newdict[num] = []
newdict[num].append(originaldict[num][0])
del originaldict[num][0]
with open(output_file, "a") as o:
for value in newdict.values():
for line in value:
o.write(line + "\n")

rassa45
- 3,482
- 1
- 29
- 43
-
If you understand what this code is doing, you should try to find a quicker way to do this by using SortedDict(). It would get of the last for loop. – rassa45 May 31 '15 at 19:48