2016-03-01 30 views
1

所以我碰上我已經開了一個.dat文件,並試圖從中提取數的情況:只保留INT在Python

self.text= (open("circles.dat", "r")).readlines() 
print (self.text) 

輸出:

['200 200 100\n', '75\t200\t15\n', ' 325\t200\t15\n', '\n', '\t200\t\t75 10\n', '200 325 10\n'] 

有沒有一種方法可以只提取int數字而不包含任何其他內容。 編輯: 的eval()不能用於 我所要的輸出是這樣的:

[200,200,100,75,200,15,325,200,15,200,75,10,200,325,10] 
+2

你應該讀行線和解析這些線路。 – RafaelC

+0

你想要一個長整數列表,還是列表列表? – zondo

+0

用於刪除\ t和\ n的東西,使用eval() – JustDucky

回答

2
>>> import re 
>>> num_list = map(int, re.findall(r'\d+', open("circles.dat", "r").read())) 
[200, 200, 100, 75, 200, 15, 325, 200, 15, 200, 75, 10, 200, 325, 10] 

使用.read()代替.readlines()爲read()返回整個文件的內容作爲一個字符串(可以與正則表達式一起使用),而不像readlines()返回字符串列表。

獲取數字列表(以字符串形式)後,使用map()函數將列表類型轉換爲int類型。

步驟解釋

>>> import re 
>>> file_content = open("circles.dat", "r").read() # Read file as single string 
>>> num_list = re.findall(r'\d+', file_content) # Fetch all numbers from string 
>>> num_list 
['200', '200', '100', '75', '200', '15', '325', '200', '15', '200', '75', '10', '200', '325', '10'] 
>>> map(int, num_list) # Typecast list of str to list of int 
[200, 200, 100, 75, 200, 15, 325, 200, 15, 200, 75, 10, 200, 325, 10] 
3

假設你擁有所有int S和它們(如空格或製表符)之間只是空格,那麼你可以使用一個簡單的列表理解與str.split()

>>> with open("circles.dat", "r") as f: 
...  d = [int(a) for l in f for a in l.split()] 
>>> d 
[200, 200, 100, 75, 200, 15, 325, 200, 15, 200, 75, 10, 200, 325, 10] 
0

無任何模塊的解決方案

>>> x = ['200 200 100\n', '75\t200\t15\n', ' 325\t200\t15\n', '\n', '\t200\t\t75 10\n', '200 325 10\n'] 
>>> 
>>> y = "".join(x) # join together 
>>> print y 
'200 200 100\n75\t200\t15\n 325\t200\t15\n\n\t200\t\t75 10\n200 325 10\n' 
>>> 
>>> z = y.replace("\t", " ").replace("\n", " ") # replace tabs and new lines 
>>> print z 
'200 200 100 75 200 15 325 200 15 200 75 10 200 325 10 ' 
>>> 
>>> z = z.split() # removes all whitespace by default 
>>> print z 
['200', '200', '100', '75', '200', '15', '325', '200', '15', '200', '75', '10', '200', '325', '10'] 
>>> 
>>> res = map(int, z) # convert all to integers 
>>> print res 
[200, 200, 100, 75, 200, 15, 325, 200, 15, 200, 75, 10, 200, 325, 10] 

解決方案作爲一個醜陋的一行(僅爲80個字符!)

res = map(int, "".join(self.text).replace("\t", " ").replace("\n", " ").split()) 
1
>>> self.text = (open("circles.dat", "r")).readlines() 
>>> print self.text 
['200 200 100\n', '75\t200\t15\n', ' 325\t200\t15\n', '\n', '\t200\t\t75 10\n', '200 325 10\n'] 
>>> 
>>> ans = map(lambda s: s.rstrip().replace("\t", " "), self.text) 
>>> ans = " ".join(ans) 
>>> ans = ans.split() 
>>> 
>>> final_ans = [int(a) for a in ans] 
>>> final_ans = map(int, ans) # alternative 
>>> print final_ans 
[200, 200, 100, 75, 200, 15, 325, 200, 15, 200, 75, 10, 200, 325, 10]