2009-01-06 17 views
2

是否有一種pythonic閱讀方式 - 說 - 混合整數和字符輸入,而無需一次讀取整個輸入,而不必擔心換行符?例如,我有一個空白分隔的數據文件,我只知道有x個整數,然後是y個字符,然後是多個整數。我不想承擔任何有關換行的信息。Python:C++ - 像流輸入

我的意思是無意識的在C以下的東西++:

...

int i, buf; 
char cbuf; 
vector<int> X, Z; 
vector<int> Y; 

for (i = 0; i < x; i++) { 
    cin >> buf; 
    X.push_back(buf); 
} 

for (i = 0; i < y; i++) { 
    cin >> cbuf; 
    Y.push_back(cbuf); 
} 

for (i = 0; i < z; i++) { 
    cin >> buf; 
    Z.push_back(buf); 
} 

編輯:我忘了說,我想它在現場輸入從控制檯表現良好好 - 即在獲得令牌之前不需要按ctrl + d,只要輸入一行,函數應該能夠返回它們。 :)

回答

2

是這樣的?

>>> data = "1 2 3 4 5 6 abcdefg 9 8 7 6 5 4 3" 

例如,我們可能會data= someFile.read()

>>> fields= data.split() 
>>> x= map(int,fields[:6]) 
>>> y= fields[6] 
>>> z= map(int,fields[7:]) 

結果

>>> x 
[1, 2, 3, 4, 5, 6] 
>>> y 
'abcdefg' 
>>> z 
[9, 8, 7, 6, 5, 4, 3] 
+0

哇,使用map(int,aList)是我不會想到的。尼斯:-) – Abgan 2009-01-06 19:44:38

3

,如果你不想在每次一整行讀得到這個,你可能想嘗試這樣的事情:

def read_tokens(file): 
    while True: 
     token = [] 
     while True: 
      c = file.read(1) 
      if c not in ['', ' ', '\t', '\n']: 
       token.append(c) 
      elif c in [' ', '\t', '\n']: 
       yield ''.join(token) 
       break 
      elif c == '': 
       yield ''.join(token) 
       raise StopIteration 

應該在文件中每次讀取一個字符時生成每個用空格分隔的標記。從那裏你應該能夠將它們轉換爲他們應該的類型。空白可能也可能更好地照顧。

6

如何返回記號流,並且表現得像cin小型發電機功能:

def read_tokens(f): 
    for line in f: 
     for token in line.split(): 
      yield token 

x = y = z = 5 # for simplicity: 5 ints, 5 char tokens, 5 ints 
f = open('data.txt', 'r') 
tokens = read_tokens(f) 
X = [] 
for i in xrange(x): 
    X.append(int(tokens.next())) 
Y = [] 
for i in xrange(y): 
    Y.append(tokens.next()) 
Z = [] 
for i in xrange(z): 
    Z.append(int(tokens.next())) 
0

這個怎麼樣?建立在heikogerlach的優秀read_tokens

def read_tokens(f): 
    for line in f: 
     for token in line.split(): 
      yield token 

我們可以做如下的事情,拿起6個數字,7個字符和6個數字。

fi = read_tokens(data) 
x= [ int(fi.next()) for i in xrange(6) ] 
y= [ fi.next() for i in xrange(7) ] 
z= [ int(fi.next()) for i in xrange(6) ]