2012-01-21 50 views
3

說我有此格式的文本文件:如何讀取文本文件到單獨列出蟒蛇

100 20個鶯飛

,我想讀INT(S)到自己的列表和字符串放入它自己的列表中......我將如何在python中進行此操作。我試過

data.append(map(int, line.split())) 

沒有工作......任何幫助?

+2

'map(int,line.split())'將'int'應用於* entire *行。是什麼讓你認爲這會將數字和單詞分開? –

回答

4

從本質上講,我讀通過行的文件行,分裂他們。我首先檢查是否可以將它們變成一個整數,如果我失敗了,將它們視爲字符串。

def separate(filename): 
    all_integers = [] 
    all_strings = [] 
    with open(filename) as myfile: 
     for line in myfile: 
      for item in line.split(' '): 
       try: 
        # Try converting the item to an integer 
        value = int(item, 10) 
        all_integers.append(value) 
       except ValueError: 
        # if it fails, it's a string. 
        all_strings.append(item) 
    return all_integers, all_strings 

然後,給定文件( 'mytext.txt')

100 20 the birds are flying 
200 3 banana 
hello 4 

...做在命令行下返回...

>>> myints, mystrings = separate(r'myfile.txt') 
>>> print myints 
[100, 20, 200, 3, 4] 
>>> print mystrings 
['the', 'birds', 'are', 'flying', 'banana', 'hello'] 
+1

+1。這種使用例外是**完美**。刪除「我不開心......」的業務。這很好。 –

+0

是的,我在某處讀到異常應該只用於特殊行爲,在這裏並不是這樣。我刪除它。 – Michael0x2a

+0

+1耶!這裏的例外是正確的。 – juliomalegria

0

pop從列表中刪除元素並返回它:

words = line.split() 
first = int(words.pop(0)) 
second = int(words.pop(0)) 

當然,這是假設你的格式始終int int word word word ...

再加入字符串的其餘部分:

words = ' '.join(words) 

而且在Python 3,你甚至可以這樣做:

first, second, *words = line.split() 

這是非常整潔。雖然您仍然必須將firstsecond轉換爲int's。

+0

你的回答是OK的。但是更通用的解決方案呢。案例是我們不知道文件中字符串和整數的出現。就像例如'hello 1 2 check'在這種情況下,您的解決方案將不起作用 – RanRag

+0

@RanRag,true。我在閱讀其他答案後按照這個假設進行編輯,但問題在這方面並不明確。如果它始終處於這種格式,我認爲Python 3單行程是最好的選擇。假設他當然使用Python 3。 –

+0

是的,在這種情況下,單線是最好的解決方案。 – RanRag

3

如果我理解正確你的問題:

import re 

def splitList(list): 
    ints = [] 
    words = [] 
    for item in list: 
     if re.match('^\d+$', item): 
      ints.append(int(item)) 
     else: 
      words.append(item) 
    return ints, words 

intList, wordList = splitList(line.split()) 

會給你兩個列表:[100, 20]['the', 'birds', 'are', 'flying']

2

這裏有一個簡單解。請注意,對於非常大的文件,其效率可能不如其他文件高,因爲它對line每次迭代word兩次。

words = line.split() 
intList = [int(x) for x in words if x.isdigit()] 
strList = [x for x in words if not x.isdigit()]