2011-06-20 27 views
2

我正在使用python,我試圖從.txt文件中提取數字,然後將它們分組爲多個類別。 .txt文件看起來是這樣的:從多條線上提取python

IF 92007<=ZIPCODE<=92011 OR ZIPCODE=92014 OR ZIPCODE=92024 

OR 92054<=ZIPCODE<=92058 OR ZIPCODE=92067 OR ZIPCODE=92075 

OR ZIPCODE=92083 OR ZIPCODE=92084 OR ZIPCODE=92091 OR ZIPCODE=92672 

OR ZIPCODE=92081 THEN REGION=1;  ** N COASTAL **; 

此代碼是用於從第一行提取號碼:

import re 

TXTPATH = 'C:/zipcode_mapping.txt' 

f = open(TXTPATH,'r') 

expr= "IF 92007<=ZIPCODE<=92011 OR ZIPCODE=92014 OR ZIPCODE=92024" 

for line in f: 
    L = line  
    print(L) 
    matches = re.findall("([0-9]{5})",expr) 
    for match in matches: 
     print match 

我似乎無法從其他線拉出數字雖然。有什麼建議麼?

回答

9

只要做到:

matches = re.findall("([0-9]{5})",f.read()) 

您可以一次提取它們都 - 沒有需要循環線。

4

難道你不需要將'expr'改爲'L'嗎?

matches = re.findall("([0-9]{5})",L) 
+0

這很好,感謝您的幫助! – BTR

1

也許我很天真,但不應該在L中搜索數字,而不是在expr中搜索數字?

matches = re.findall("([0-9]{5})", L) 
           ^^^^^^