I'm working with python and am trying to extract numbers from a .txt file and then group them into multiple categories. The .txt file looks like this:
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 **;
This code was used to extract numbers from the first line:
import re
TXTPATH = 'C:/zipcode_mapping.txt'
f = open(TXTPATH,'r')
expr= "IF 92007<=ZIPCODE<=92011 OR ZIPCODE=92014 OR ZIPCOD开发者_开发百科E=92024"
for line in f:
L = line
print(L)
matches = re.findall("([0-9]{5})",expr)
for match in matches:
print match
I can't seem to pull out the numbers from the other lines though. Any suggestions?
Just do:
matches = re.findall("([0-9]{5})",f.read())
You can extract them all at once - no need to loop over lines.
Don't you just need to change 'expr' to 'L'?
matches = re.findall("([0-9]{5})",L)
Maybe I'm being naive, but shouldn't you search for numbers in L, instead of in expr?
matches = re.findall("([0-9]{5})", L)
^^^^^^
精彩评论