简体   繁体   English

如何从字符串python中提取特定变量?

[英]How to extract specific variables from a string python?

I have a string like "A:22.0 /4.03 B:15.05 /3.0 C:120.15 /12.4" (with the spaces). 我有一个字符串,例如"A:22.0 /4.03 B:15.05 /3.0 C:120.15 /12.4" (带空格)。


I want to extract the numbers and to store them intro variables with specific names. 我想提取数字并将它们存储在具有特定名称的介绍变量中。 For the example, i want to have the variable A1 = 22.0 , A2 = 4.03 , B1 = 15.05 , B2 = 3.0 , C1 = 120.15 , C2 = 12.4 例如,我想要变量A1 = 22.0A2 = 4.03B1 = 15.05B2 = 3.0C1 = 120.15C2 = 12.4
The variables in the string might not be in this order, but there will always be groups of: 字符串中的变量可能不按此顺序排列,但是总会有以下组:
(variable name):(value1) /(value2) in this order. (variable name):(value1) /(value2)以此顺序。

Any help or idea is appreciated. 任何帮助或想法表示赞赏。 Thank you! 谢谢!

There are a million ways to do this. 有百万种方法可以做到这一点。 Regular expressions are great and can be helpful for missing values and other edge cases. 正则表达式非常有用,对于缺失值和其他边缘情况可能很有帮助。 Assuming your data is never missing a value or in any other format a simple string replacement and split can do the job. 假设您的数据绝不会缺少任何值或任何其他格式,那么简单的字符串替换和拆分就可以完成任务。

You'll find it difficult name variables based on values from a string (A1, A2, etc). 您会发现很难根据字符串(A1,A2等)中的值来命名变量。 It's better to use a dictionary to store this type of data. 最好使用字典来存储这种类型的数据。

The complex part of this is the construction of the dictionary, which in this case is counting from 0 to the length of items in the split list, by 3s, and using those numbers to create the key:value pairs of the dictionary. 复杂的部分是字典的构造,在这种情况下,字典的计数是从0到拆分列表中项的长度乘以3s,然后使用这些数字创建字典的key:value对。

Original String 原始字符串

x = "A:22.0 /4.03 B:15.05 /3.0, C:120.15 /12.4"

Replace special characters w/space and split on spaces (will remove extra whitespace) 用空格替换特殊字符并在空格上分割(将删除多余的空格)

b = x.replace(':',' ').replace('/',' ').split()

Gives you 给你

['A', '22.0', '4.03', 'B', '15.05', '3.0,', 'C', '120.15', '12.4']

Construct a dictionary from your data 根据您的数据构建字典

output = {b[x]:[b[x+1],b[x+2]] for x in range(0,len(b),3)}

Output: 输出:

{'A': ['22.0', '4.03'], 'B': ['15.05', '3.0,'], 'C': ['120.15', '12.4']}

Then access the data as such: 然后这样访问数据:

output['A'][0]
22.0
output['A'][1]
4.03

To extract them, you should use Regex: here is the documentation: RegEx (Python) 要提取它们,您应该使用Regex:这是文档: RegEx(Python)

But I recommend you to take a look at dictionaries. 但是我建议您看一下字典。 It will provide a control of keys and values, it looks what you need. 它将提供对键和值的控制,看起来像您所需要的。 Here is an example: 这是一个例子:

variableName = {
        "A1":22.0,
        "A2":4.03
    }

Here is the link to a good tutorial of how to use this: https://www.pythonforbeginners.com/dictionary/how-to-use-dictionaries-in-python/ 这是有关如何使用它的一个很好的教程的链接: https : //www.pythonforbeginners.com/dictionary/how-to-use-dictionaries-in-python/

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

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