简体   繁体   English

从python中提取多行

[英]Extraction from python over multiple lines

I'm working with python and am trying to extract numbers from a .txt file and then group them into multiple categories. 我正在使用python并尝试从.txt文件中提取数字,然后将它们分组为多个类别。 The .txt file looks like this: .txt文件如下所示:

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 ZIPCODE=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. 您可以一次性提取所有内容 - 无需循环遍历。

你不是只需要将'expr'改为'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? 也许我很天真,但你不应该在L中搜索数字,而不是在expr中搜索?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM