![](/img/trans.png)
[英]How to extract text part from file using Python & Regular Expressions
[英]Using Regular Expressions to extract numerical quantities from a file and find the sum
我是一個初學者,正在學習python。 問題是我必須從文件中提取數字(其中數字可以在任何地方。可以在同一行中多次。某些行可能沒有數字,而某些行可能是新行)並找到它們的總和。 我確實知道如何解決它,這是我的代碼
import re
new=[]
s=0
fhand=open("sampledata.txt")
for line in fhand:
if re.search('^.+',line): #to exclude lines which have nothing
y=re.findall('([0-9]*)',line) #this part is supposed to extract only the
for i in range(len(y)): #the numerical part, but it extracts all the words. why?
try:
y[i]=float(y[i])
except:
y[i]=0
s=s+sum(y)
print s
該代碼可以工作,但是它不是實現此目的的Python方法。 為什么[[0-9] *)提取所有單詞而不是僅提取數字? pythonic的實現方法是什么?
您的正則表達式具有([0-9]*)
,它將查找具有零個或多個數字的所有單詞。 您可能需要([0-9]+)
。
您好,您通過添加“ *”在正則表達式中犯了一個錯誤,如下所示:
y=re.findall('([0-9])',line)
擴展wind85的答案后,您可能希望根據希望在文件中找到的數字類型來微調正則表達式。 例如,如果您的數字中可能帶有小數點,那么您可能想要類似[0-9]+(?:\\.[0-9]+)?
(一個或多個數字(可選),后跟一個句點和一個或多個數字)。
至於使它更具pythonic風格,我可能會這樣寫:
s=0
for line in open("sampledata.txt"):
s += sum(float(y) for y in re.findall(r'[0-9]+',line))
print s
如果您真的想花哨的話,可以將它設為單線:
print sum(float(y) for line in open('sampledata.txt')
for y in re.findall(r'[0-9]+',line))
但是我個人覺得這種事情很難閱讀。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.