从字符串中提取值的简单方法

2024-04-25 04:01:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下字符串:

s = '''Report:

      Location: (569P,921L)

      Band 1:

        Value: 12'''

我必须得到以下信息:

x, y = 569, 921

最好最简单的方法是什么?你知道吗

我不喜欢re,因为使用它的特点复杂而混乱。你知道吗

我已经成功地提取了我需要的内容,如下所示:

x, y = int(s.split()[2].split(',')[0][1:-1]), int(s.split()[2].split(',')[1][:-2])

但你的想法很受赞赏。你知道吗


Tags: 方法字符串reportre信息内容bandvalue
3条回答

Report:\s*Location:\s*\(([0-9]*)P,([0-9]*)L\)\s*Band 1:\s*Value: 12

这个正则表达式应该适合你的情况

完整代码:

m = re.match(
    r"Report:\s*Location:\s*\(([0-9]*)P,([0-9]*)L\)\s*Band 1:\s*Value: 12",
    your_string)
m.group(0)      # First Number
m.group(1)      # Second Number`

这个简单的正则表达式适用于这种情况。你知道吗

>>> s = '''Report:

  Location: (569P,921L)

  Band 1:

    Value: 12'''
>>> x,y = re.findall(r'\b\d+(?=[A-Z])', s)
>>> print(x,y)
569 921

\b匹配单词字符和非单词字符的单词边界。\d+匹配一个或多个数字,(?=[A-Z]),后面必须跟一个大写字母。你知道吗

按字符串查找方法: 介于()之间的目标内容

import traceback

lines = input.split("\n")
result = []
for i in lines:
    start_index = i.find("(")
    if start_index!=-1:
        end_index = i.find(")", start_index)
        if end_index!=-1:
            taget_content = i[start_index+1: end_index]
            tmp = taget_content.split(",")
            try:
                x = int(tmp[0][:-1])
                y = int(tmp[1][:-1])
                result.append((x,y))
            except:
                print "Exception during eval:-", traceback.format_exc() 

print result

输出:

$ python test.py 
[(569, 921), (600, 900)]

通过正则表达式

input = '''Report:

      Location: (569P,921L)

      Band 1:

        Value: 12
      Location: (600P,900L)

      Band 1:

        Value: 12
        '''

import re

target = re.findall("\((.*)\)", input)
print "target content:-", target
result = []
for i in target:
    tmp = i.split(",")
    try:
        result.append((int(tmp[0][:-1]), int(tmp[1][:-1])))
    except:
         print "Exception during eval:-", traceback.format_exc() 


print "Result:-", result

输出:

$ python test.py 
target content:- ['569P,921L', '600P,900L']
Result:- [(569, 921), (600, 900)]

相关问题 更多 >