2013-09-22 22 views
0

我用Python寫了一個腳本字符串(x,y座標)的兩列之間刪除選項卡/空格加上一個逗號分隔欄和上市的最大和每列的最小值(每個x和y座標的值爲2)。例如:的Python腳本trasnforming ANS以升序排序列,小數情況下

100000.00 60000.00 
200000.00 63000.00 
300000.00 62000.00 
400000.00 61000.00 
500000.00 64000.00 

變成了:

100000.00,60000.00 
200000.00,63000.00 
300000.00,62000.00 
400000.00,61000.00 
500000.00,64000.00 

10000000 50000000 60000000 640000000 

這是我使用的代碼:

import string 
input = open(r'C:\coordinates.txt', 'r') 
output = open(r'C:\coordinates_new.txt', 'wb') 
s = input.readline() 
while s <> '': 
    s = input.readline() 
    liste = s.split() 
    x = liste[0] 
    y = liste[1] 
    output.write(str(x) + ',' + str(y)) 
    output.write('\n') 
    s = input.readline() 
input.close() 
output.close() 

我需要改變上面的代碼也由兩個小數變換座標到小數點後一位值和兩個新列中的每一列都將根據x座標(左列)的值以升序排序。

我開始寫下面的,但它不僅是沒有排序的值,它是放置在左側和右側的x y座標。另外我不知道如何轉換小數,因爲這些值是字符串,我知道的唯一函數是使用%f並且需要浮點數。有什麼建議來改進下面的代碼?

import string 
input = open(r'C:\coordinates.txt', 'r') 
output = open(r'C:\coordinates_sorted.txt', 'wb') 
s = input.readline() 
while s <> '': 
    s = input.readline() 
    liste = string.split(s) 
    x = liste[0] 
    y = liste[1]  
    output.write(str(x) + ',' + str(y))  
    output.write('\n') 
    sorted(s, key=lambda x: x[o]) 
    s = input.readline() 
input.close() 
output.close() 

謝謝!

+0

首先你說代碼給出了錯誤的輸出,然後你說它給了一個'IndexError'。這是什麼?在我看來,它實際上會引發'NameError',因爲沒有分配'o'。 – interjay

+0

什麼意思是「轉換小數」,我不明白你想在這裏做什麼。你能舉一些例子嗎? –

+0

@Tim Pietzcker:通過改變小數我的意思,而不是兩個十進制值xxxx.oo我想代碼將它們更改爲一個十進制值xxx.o – GeoLuCa

回答

0

首先,嘗試格式化根據PEP8代碼-it'll更容易閱讀。 (我已經在你的文章中完成了清理)。

其次,蒂姆是正確的,你應該嘗試學習如何編寫代碼(地道)的Python彷彿直接從它的等價的C編譯不公平。

作爲一個起點,我會在這裏發表您的第二個片段,重構爲地道的Python:

# there is no need to import the `string` module; `.strip()` is a built-in 
# method of strings (i.e. objects of type `str`). 

# read in the data as a list of pairs of raw (i.e. unparsed) coordinates in 
# string form: 
with open(r'C:\coordinates.txt') as in_file: 
    coords_raw = [line.strip().split() for line in in_file.readlines()] 

# convert the raw list into a list of pairs (2-tuples) containing the parsed 
# (i.e. float not string) data: 
coord_pairs = [(float(x_raw), float(y_raw)) for x_raw, y_raw in coords_raw] 

coord_pairs.sort() # you want to sort the entire data set, not just values on 
        # individual lines as in your original snippet 

# build a list of all x and y values we have (this could be done in one line 
# using some `zip()` hackery, but I'd like to keep it readable (for you at 
# least)): 
all_xs = [x for x, y in coord_pairs] 
all_ys = [y for x, y in coord_pairs] 
# compute min and max: 
x_min, x_max = min(all_xs), max(all_xs) 
y_min, y_max = min(all_ys), max(all_ys) 

# NOTE: the above section performs well for small data sets; for large ones, you 
# should combine the 4 lines in a single for loop so as to NOT have to read 
# everything to memory and iterate over the data 6 times. 

# write everything out 
with open(r'C:\coordinates_sorted.txt', 'wb') as out_file: 
    # here, we're doing 3 things in one line: 
    # * iterate over all coordinate pairs and convert the pairs to the string 
    #  form 
    # * join the string forms with a newline character 
    # * write the result of the join+iterate expression to the file 
    out_file.write('\n'.join('%f,%f' % (x, y) for x, y in coord_pairs)) 

    out_file.write('\n\n') 
    out_file.write('%f %f %f %f' % (x_min, x_max, y_min, y_max)) 

with open(...) as <var_name>給你的文件句柄與try-finally的保證關閉;此外,它短於分開的行上的open(...).close()。另外,with可用於其他目的,但通常用於處理文件。我建議你看看如何使用try-finally以及with /上下文管理在Python中,除了一切你可以在這裏學到。

+0

Hi Erik。非常感謝您一步一步來完成。非常感謝,因爲1)它的工作原理(我只需要在最後添加所需的小數長度)和2)我學到了一些東西。它可能看起來像C語言的原因是,這是我的講師教我的方式(我根本不懂C語言; Python是我第一次嘗試編程,因此我缺乏技能)。 你和蒂姆對於使用更多慣用編碼都是正確的,但希望這會隨着時間的推移而越來越多,我在手冊/教程中閱讀更多,並嘗試這樣的練習。 – GeoLuCa

0

你的代碼看起來更象C不是像Python;這是相當單一的。我建議你閱讀Python tutorial尋找靈感。例如,使用while循環進行迭代通常是錯誤的方法。該string模塊已被棄用大部分,<>應該是!=,你並不需要調用str()的對象已經是一個串上...

然後,存在一些誤區。例如,sorted()返回你傳遞可迭代的排序版本 - 你需要來指派的東西,否則結果將被丟棄。但是,你在一個字符串上調用它,無論如何,這不會給你想要的結果。你也寫了x[o],你明確表示x[0]

您應該使用這樣的(假設的Python 2):

with open(r'C:\coordinates.txt') as infile: 
    values = [] 
    for line in infile: 
     values.append(map(float, line.split())) 
values.sort() 
with open(r'C:\coordinates_sorted.txt', 'w') as outfile: 
    for value in values: 
     outfile.write("{:.1f},{:.1f}\n".format(*value))