2016-09-17 39 views
0

我有一個文本文件,其中包含文本中的整數。一行或一行中有一個或多個整數。我想用正則表達式找到這些整數並計算總和。正則表達式對文本的Python列表解析

我已成功地編寫代碼:

import re 
doc = raw_input("File Name:") 
text = open(doc) 
lst = list() 
total = 0 

for line in text: 
    nums = re.findall("[0-9]+", line) 
    if len(nums) == 0: 
     continue 
    for num in nums: 
     num = int(num) 
     total += num 
print total 

,但我也想知道清單理解的版本,有人可以幫忙嗎?

+0

順便說一句......你不需要'如果len(nums)== 0'。如果沒有,for循環將不會做任何事情。 – zvone

+0

@zvone感謝您的信息 –

回答

1

既然您想在找到它們之後計算數字的總和,最好在sum()範圍內使用re.finditer()的生成器表達式。另外,如果文件的大小不是非常大,則最好一次讀取它,而不是一次讀取一行。

import re 
doc = raw_input("File Name:") 
with open(doc) as f: 
    text = f.read() 

total = sum(int(g.group(0)) for g in re.finditer(r'\d+', text)) 
+0

謝謝,並且還有一個雙線版本可以幫助你:'進口號 打印總和([__________('[0-9] +',_________。read())] )' –

+0

@ user6561340沒有必要把它寫成兩行。但是如果你想練習,就試試看看結果。 – Kasramvd

+0

感謝您的幫助:) –