简体   繁体   English

如何从 Python 中的字符串中提取特定字符?

[英]How to extract specific characters from a string in Python?

say I have a string like this:说我有一个这样的字符串:

coordinates:x=22,y=45;x=144,y=56;x=26,y=13;x=144,y=87

and I want to store the values in 8 variables:我想将值存储在 8 个变量中:

xCoord1 = 22
yCoord1 = 45
xCoord2 = 144
yCoord2 = 56
xCoord3 = 26
yCoord3 = 13
xCoord4 = 144
yCoord4 = 87

Note: coordinates could be 2 or 3 digits long only.注意:坐标只能是 2 或 3 位数字。

Better create a dictionary to hold the output.最好创建一个字典来保存 output。

You can use re.findall to extract the key/values and a dictionary comprehension to generate the output.您可以使用re.findall提取键/值和字典理解来生成 output。

The auto incrementation of the keys can be done with a combination of collections.defaultdict and itertools.count键的自动递增可以通过collections.defaultdictitertools.count的组合来完成

s = 'coordinates:x=22,y=45;x=144,y=56;x=26,y=13;x=144,y=87'

import re
from itertools import count
from collections import defaultdict

counter = defaultdict(lambda:count())

coords = {f'{k}Coord{next(counter[k])+1}': int(v)
          for k,v in re.findall('(\w+)=(\d+)', s)}

output: output:

{'xCoord1': 22,
 'yCoord1': 45,
 'xCoord2': 144,
 'yCoord2': 56,
 'xCoord3': 26,
 'yCoord3': 13,
 'xCoord4': 144,
 'yCoord4': 87}

Then access your values by selecting the coordinated by name:然后通过按名称选择协调来访问您的值:

>>> coords['xCoord1']
22
tuples as keys:元组作为键:

I would even prefer to use tuples as keys:我什至更喜欢使用元组作为键:

counter = defaultdict(lambda:count())
coords = {(k, next(counter[k])+1): int(v)
          for k,v in re.findall('(\w+)=(\d+)', s)}

coords['x', 1]
# 22

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

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