2015-09-27 76 views
2

我想按字母順序重新排列文件。另外我希望將數字打印在已排列的字母旁邊。如何按字母順序重新排列?

如:

a 4 
c 5 
e 6 
f 2 

這裏是我的代碼:

f = open("1.txt","r") 
r = f.read() 
print(r) 
r=r.split() 

line=sorted(r) 
for row in line: 
    print(line) 

和這裏的結果我得到:

f 2 
c 5 
e 6 
a 4 
['2', '4', '5', '6', 'a', 'c', 'e', 'f'] 
['2', '4', '5', '6', 'a', 'c', 'e', 'f'] 
['2', '4', '5', '6', 'a', 'c', 'e', 'f'] 
['2', '4', '5', '6', 'a', 'c', 'e', 'f'] 
['2', '4', '5', '6', 'a', 'c', 'e', 'f'] 
['2', '4', '5', '6', 'a', 'c', 'e', 'f'] 
['2', '4', '5', '6', 'a', 'c', 'e', 'f'] 
['2', '4', '5', '6', 'a', 'c', 'e', 'f'] 
>>> 
+0

我的代碼的頂部有點搞砸了,我是這個websire的新手。 –

+0

我假設你的意思是'排成行:print(row)'not'print(line)';答案中解決了其他問題。 – ShadowRanger

回答

2

爲了得到對在子列表mapstr.split對文件對象和調用排序:

with open("in.txt") as f: 
    print(sorted(map(str.split,f))) 

in.txt:

e 6 
c 5 
f 2 
a 4 

輸出:

[['a', '4'], ['c', '5'], ['e', '6'], ['f', '2']] 

排序文件按字母順序剛開您只需調用該文件對象的排序行:

with open("test.txt") as f: 
    print(sorted(f)) 

如果要格式化輸出:

with open("test.txt") as f: 
    for sub in sorted(map(str.split,f)): 
     print("letter = {}, num = {}".format(*sub)) 

letter = a, num = 4 
letter = c, num = 5 
letter = e, num = 6 
letter = f, num = 2 

也是爲什麼你看到['2', '4', '5', '6', 'a', 'c', 'e', 'f']是因爲調用各執.read所有的數據分割成一個單一的列表,拆分,拆分任何空格,當字典順序比較字符串的數字字母數字被認爲是較低的SO 2 <一,請注意,在比較字符串數字時,如果字符串被比較爲11 > 100 = True作爲字符串被比較爲1被認爲大於0當比較數字與int比較時,100會出現在排序列表中的11之前。

如果你想擁有的每個用戶始終保持最近三年得分最高,你可以使用一個deque以3 maxlen和初始排序pickle了字典之後。

from csv import reader 
from collections import deque, OrderedDict 
import pickle 
name, new_score = "foo",100 
with open("test.txt") as f: 
    d = OrderedDict((name, deque(map(int,rest),maxlen=3)) for name, *rest in reader(sorted(f))) 
    print(d) 
    d[name].append(new_score) 
    print(d) 

with open("my_data.pkl","wb") as out: 
    pickle.dump(d, out) 


with open("my_data.pkl","rb") as out: 
    print(pickle.load(out)) 

的test.txt:

homer,2 
foo,1,2,3 
bar,4,5,6 

輸出:

OrderedDict([('bar', deque([4, 5, 6], maxlen=3)), ('foo', deque([1, 2, 3], maxlen=3)), ('homer', deque([2], maxlen=3))]) 
OrderedDict([('bar', deque([4, 5, 6], maxlen=3)), ('foo', deque([2, 3, 100], maxlen=3)), ('homer', deque([2], maxlen=3))]) 
OrderedDict([('bar', deque([4, 5, 6], maxlen=3)), ('foo', deque([2, 3, 100], maxlen=3)), ('homer', deque([2], maxlen=3))]) 

一旦整理你只需要加載得到快譯通,你已經寫了後傾。

+0

謝謝你這就是我需要我也想問你另一個問題,我有另一個程序寫入這個文本文件,我想保存3個數字爲一個字母我怎麼做?再次感謝 –

+0

你的意思是再增加兩個數字? –

+0

不,它應該像這樣一個1,2,3 b 4,399 –

0

您需要使用readlines()而不是read()來獲取文件的每一行作爲列表的單獨元素。然後,一個簡單的列表將起作用。

f = open('1.txt','r') 

# Use readlines isntead of of read to get an list of lines 
lines = f.readlines() 
print ''.join(lines) 

# Now sort the list (default is by first letter 
lines.sort() 
print ''.join(lines) 

或者,您可以強制使用行尾字符'\ n'而不是默認的全部空格。但是現在你需要用新行char('\ n')加入列表而不是空字符串。

f = open('1.txt','r') 
lines = f.read() 
lines = lines.split('\n') 
print '\n'.join(lines) 

# Now sort the list (default is by first letter 
lines.sort() 
print '\n'.join(lines)