简体   繁体   English

从字符串中提取数字的pythonic方法

[英]pythonic method for extracting numeric digits from string

I am developing a program to read through a CSV file and create a dictionary of information from it.我正在开发一个程序来读取 CSV 文件并从中创建信息字典。 Each line in the CSV is essentially a new dictionary entry with the delimited objects being the values. CSV 中的每一行本质上是一个新的字典条目,其中分隔对象是值。

As one subpart of task, I need to extract an unknown number of numeric digits from within a string.作为任务的一个子部分,我需要从字符串中提取未知数量的数字。 I have a working version, but it does not seem very pythonic.我有一个工作版本,但它似乎不是很pythonic。

An example string looks like this:示例字符串如下所示:

variable = Applicaiton.Module_Name.VAR_NAME_ST12.WORD_type[0]

variable is string's name in the python code, and represents the variable name within a MODBUS. variable是 python 代码中的字符串名称,表示 MODBUS 中的变量名称。 I want to extract just the digits prior to the .WORD_type[0] which relate to the number of bytes the string is packed into.我只想提取.WORD_type[0]之前的数字,这些数字与字符串打包到的字节数有关。

Here is my working code, note this is nested within a for statement iterating through the lines in the CSV.这是我的工作代码,请注意,它嵌套在 for 语句中,该语句遍历 CSV 中的行。 var_length and var_type are some of the keys , ie {"var_length": var_length} var_lengthvar_type是一些keys ,即{"var_length": var_length}

if re.search(".+_ST[0-9]{1,2}\\.WORD_type.+", variable):
    var_type = "string"
    temp = re.split("\\.", variable)
    temp = re.split("_", temp[2])
    temp = temp[-1]
    var_length = int(str.lstrip(temp, "ST")) / 2

You could maybe try using matching groups like so:您可以尝试使用这样的匹配组:

import re

variable = "Applicaiton.Module_Name.VAR_NAME_ST12.WORD_type[0]"
matches = re.match(r".+_ST(\d+)\.WORD_type.+", variable)
if matches:
    print(matches[1])

matches[0] has the full match and matches[1] contains the matched group. matches[0]包含完整匹配, matches[1]包含匹配组。

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

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