2014-04-09 59 views
0

我:如何將字符串拆分爲不同的值?

file=open("file.txt","r") 

,文件的格式爲:

apple\red\3 months 
pear\green\4 months 

我怎麼分割文件,使其成爲以列表的形式:

fruit = ['apple', 'pear'] 
colour = ['red','green'] 
expire = ['3 months', '4 months'] 

我絕對不知道,並會感謝幫助。我現在擁有的一切:

file = open('file.txt','r') 
for i in file: 
    i.readline() 
    i.split('\ ') 

不知道這是正確的,但有當我把它拆分成的形式,不知道:

apple 
red 
3 months 
pear 
green 
4 months 

如何使第一次和每之後的第3排進入列表,以及之後的第2和第3排,等等。

回答

1

你能做到這一點,如下所示:

s = ['apple\red\3 months', 'pear\green\4 months'] 

fruit = [i[0] for i.split('\\') in s] 
colour = [i[1] for i.split('\\') in s] 
expire = [i[2] for i.split('\\') in s] 
3

您可以分割線和各部件添加到列表中。例如:

fruit = [] 
colour = [] 
expire = [] 

file = open('file.txt','r') 
for i in file: 
    fruit_, colour_, expire_ = i.split('\\') 
    fruit.append(fruit_) 
    colour.append(colour_) 
    expire.append(expire_) 
+1

你完全可以簡化爲'fruit_,colour_,expire_ = i.split( 「\\」) ',然後'使用更有意義的變量名追加',儘管如果該行不符合預期,這會引發錯誤。 – jonrsharpe

+0

@jonrsharpe是的。完成。謝謝! – locoyou

+0

如果OP想要在每一行添加更多的東西,這不是很容易擴展。 –

0
for l in open("i.txt"): 
    for m in l.split('\\'): 
     print(m.strip()) 
0

你正常的時候。

fruit = [] 
color = [] 
expire = [] 
file = open('file.txt','r') 
for i in file: 
     i.readline() 
     f, c, exp = i.split('\\') 
     fruit.append(f) 
     color.append(c) 
     expire.append(exp) 
0

使用zip*

>>> s = r'''apple\red\3 months 
pear\green\4 months''' 
>>> zip(*(x.rstrip().split('\\') for x in s.splitlines())) 
[('apple', 'pear'), ('red', 'green'), ('3 months', '4 months')] 

因爲你可以這樣做一個文件:

with open("file.txt") as f: 
    fruit, colour, expire = zip(*(line.rstrip().split('\\') for line in f)) 

zip返回元組而不是列表,這樣你就可以使用它們轉換成列表list()

0
fruit, color, expire = [], [], [] 
for i in open('file.txt'): 
     fr,col,exp = i.split('\\') 
     fruit.append(fr) 
     color.append(col) 
     expire.append(exp) 
print fruit #['apple', 'pear'] 
print color #['red', 'green'] 
print expire #['red', 'green'] 
1

您可以使用.split()方法使用序列解包,然後將每個值添加到其單獨的列表中。請注意,反斜槓用於轉義特殊序列,因此您必須用反斜槓轉義反斜槓,然後拆分'\\'

>>> line = 'apple\red\3 months' 
>>> line = line.split('\\') 
>>> line 
['apple', 'red', '3 months'] 
>>> fruit, colour, expire = line 
>>> print(fruit, colour, expire) 
apple red 3 months 

從文件中讀取數據時,你還必須.strip()每一行,因爲他們在最後換行符。解決方案:

data = {'fruits': [], 'colours': [], 'expires': []} 

with open('file.txt') as f: 
    for line in f: 
     fruit, colour, expire = line.strip().split('\\') 
     data['fruits'].append(fruit) 
     data['colours'].append(colour) 
     data['expires'].append(expire) 

可擴展版本:

columns = ['fruits', 'colours', 'expires'] 
data = {c: [] for c in columns} 

with open('file.txt') as f: 
    for line in f: 
     line = line.strip().split('\\') 
     for i, c in enumerate(columns): 
      data[c].append(line[i]) 

未經測試的一行:

with open('file.txt') as f: data = {c: d for c, *d in zip(*(['fruits', 'colours', 'expires']+[line.strip().split('\\') for line in f]))}