如何从Python中的类似字符串中获取值?

时间:2013-11-17 16:02:53

标签: python regex expression

假设我有一个包含类似字符串的文件中的以下字符串:

Andorra la Vella|ad|Andorra la Vella|20430|42.51|1.51|
Canillo|ad|Canillo|3292|42.57|1.6|
Encamp|ad|Encamp|11224|42.54|1.57|
La Massana|ad|La Massana|7211|42.55|1.51|
...

如何使用正则表达式打印第一个数字(或每个字符串的第四个字段)? 而且,如果第四个数字超过10000,我如何打印特定行的前4个字段(例如“Andorra la Vella”“ad”“Andorra la Vella”20430)?

4 个答案:

答案 0 :(得分:5)

我认为在这种情况下使用csv模块会更容易:

import csv
with open(filename, 'rb') as f:
    for row in csv.reader(f, delimiter='|'):
        num = float(row[3])
        if num > 10000:
            print(row[:4])

答案 1 :(得分:2)

您不需要正则表达式。

s = """
Andorra la Vella|ad|Andorra la Vella|20430|42.51|1.51|
Canillo|ad|Canillo|3292|42.57|1.6|
Encamp|ad|Encamp|11224|42.54|1.57|
La Massana|ad|La Massana|7211|42.55|1.51|
"""

for line in s.splitlines():  # pretend we are reading from a file
    if not line:
        continue # skip empty lines

    groups = line.split('|')  # splits each line into its segments
    if int(groups[3]) > 10000:  # checks if the 4th value is above 10000
        print groups[:4]  # prints the first 4 values
    else:
        print groups[3]  # prints the 4th value

>>> 
['Andorra la Vella', 'ad', 'Andorra la Vella', '20430']
3292
['Encamp', 'ad', 'Encamp', '11224']
7211

答案 2 :(得分:1)

使用正则表达式

import re
results = [re.match('(.*?\|)(.*?\|)(.*?\|)(.*?\|)(.*?\|)(.*?\|)', line).groups() for line in open('file.txt')]
# filter just the rows with fourth column > 10000
results = [result for result in results if int(result[3]) > 10000]

使用拆分

results = [line.split('|')[0:-1] for line in open('file.txt')]
# filter just the rows with fourth column > 10000
results = [result for result in results if int(result[3]) > 10000]

答案 3 :(得分:0)

此处不需要正则表达式,您可以使用str.splitstr.strip

>>> s = 'Andorra la Vella|ad|Andorra la Vella|20430|42.51|1.51|'
>>> spl = s.rstrip('|\n').split('|')
>>> spl
['Andorra la Vella', 'ad', 'Andorra la Vella', '20430', '42.51', '1.51']
if int(spl[3]) > 10000:
    print (spl[:3])
...     
['Andorra la Vella', 'ad', 'Andorra la Vella']

<强>演示:

with open('filename') as f:
    for line in f:
        data = line.rstrip('|\n').split('|')
        if int(data[3]) > 10000:
            print data[:4]

<强>输出:

['Andorra la Vella', 'ad', 'Andorra la Vella', '20430']
['Encamp', 'ad', 'Encamp', '11224']