2014-11-09 27 views
-3

我想從文件中提取數字(整數和浮點數)(排除所有特殊符號和字母)。來自所有職位的數字。如何僅從輸入文件中提取數字。數字可以是float/int

import re 
file = open('input_file.txt', 'r') 
file = file.readlines() 

for line in file: 
    line=re.findall(r'\d+|\d+.\d+', line) 
    print line 
+1

請說明你有問題嗎?你想達到什麼目的? – muthan 2014-11-09 03:31:42

+0

這是我的輸入文件 - 我想從文件中提取所有數字。 12asdasdsa 33asdsad 44 aidsasdd 2231%#@ qqq55 2222ww WW QQ 1asdasd 33 ## $ 11 42.09 $ 12 – janhavi 2014-11-09 03:53:43

回答

3

也許這會有所幫助。

string這裏可以是你的line。我只是放入了虛擬文本。

import re 

string = "He is 100, I am 18.5 and we are 0.67. Maybe we should 100, 200, and 200b 200, 67.88" 

s = re.findall(r"[-+]?\d*\.\d+|\d+", string) 

print(s) 

吐出當被執行時執行以下操作:

['100', '18.5', '0.67', '100', '200', '200', '200', '67.88'] 

實驗

我上弗蘭肯斯坦的部分進行語料庫一個小實驗。

注意我使用.read()來讀取整個文件,而不是逐行處理。

import re 

file = open('frank.txt', 'r') 

file = file.read() 

numbers = re.findall(r"[-+]?\d*\.\d+|\d+", file) 

print(numbers) 

這是結果:

['17', '2008', '84', '1', '11', '17', '2', '28', '17', '3', '7', '17', '4', '5', '17', '31', '13', '17', '19', '17', '1', '2', '3', '4', '5', '6', '18', '17', '7', '7', '12', '17', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '27', '20', '21', '22', '18', '17', '23', '24', '26', '17', '2', '5', '7', '12', '9', '11', '84', '84', '8', '84', '1', '1', '1', '.8', '1', '1', '1', '1', '1', '1', '1', '.1', '1', '.2', '1', '.1', '1', '.7', '1', '.8', '1', '.9', '1', '.3', '1', '.1', '1', '.7', '1', '.4', '1', '.5', '1', '.1', '1', '.6', '1', '.1', '1', '.7', '1', '.8', '1', '.9', '1', '.8', '20', '60', '4', '30', '1', '.3', '90', '1', '.9', '3', '1', '1', '.1', '1', '.2', '1', '.3', '3', '1', '.3', '90', '1', '.4', '1', '.3', '1', '.5', '1', '.6', '2', '2001', '3', '4', '3', '501', '3', '64', '6221541', '501', '3', '4557', '99712', '809', '1500', '84116', '801', '596', '1887', '4', '1', '5', '000', '50', '5'] 

單元測試

我寫的與您提供的字符串工作的輕型版本。

import unittest 
import re 


# Extract numbers improved 
def extract_numbers_improved(x): 

    numbers = re.findall(r"[-+]?\d*\.\d+|\d+", x) 

    return numbers 


# Unit Test 
class Test(unittest.TestCase): 
    def testcase(self): 

     teststr = "12asdasdsa 33asdsad 44 aidsasdd 2231%#@ qqq55 2222ww ww qq 1asdasd 33##$11 42.09 12$" 
     self.assertEqual(extract_numbers_improved(\ 
      teststr), ['12', '33', '44', '2231', '55', '2222', '1', '33', '11', '42.09', '12']) 

unittest.main() 

當事情過去,這給綠色信號,如下圖所示:

Ran 1 test in 0.000s 

OK 
+0

謝謝!即使這個按預期工作 – janhavi 2014-11-09 04:07:43

+0

隨時。還爲你的細讀增加了單元測試。 – 2014-11-09 04:12:55

+1

由於在替代選項周圍沒有parens,所以'[+ - ]'只能匹配十進制數字。 – smathy 2014-11-11 03:35:29

0
re.findall("[+-]?\d+\.?\d*",some_text) 

我認爲至少

[+-]? 0或+或一個 - (即可選)

\d+一個或多個數字

\.?任選十進制

\d*零個或多個附加號碼

+0

好於正則表達式部分解釋一起關注一下:) – 2014-11-09 04:15:30

3

沒有說明,您可以嘗試以下操作。

re.findall(r'[+-]?\d+(?:\.\d+)?', line) 
+0

很好的答案提前...也許更好因爲我的匹配'36.'可能或不可取 – 2014-11-09 03:38:03

+0

謝謝!它完美的工作! – janhavi 2014-11-09 04:05:44

相關問題