Skip to main content
 首页 » 编程设计

python之你如何将文本放入python中的数组中

2025年05月04日12Renyi-Fan

我有一个这样的变量:

metricName = '(WebSpherePMI\|jvmRuntimeModule:ProcessCpuUsage)|(WebSpherePMI\|threadPoolModule\|WebContainer:ActiveCount)|(GC Monitor\|Memory Pools\|Java heap:Percentage of Maximum Capacity Currently Used)|(GC Monitor\|Garbage Collectors\|(.*):GC Invocations Per Interval Count)|(GC Monitor\|Garbage Collectors\|(.*):GC Time Per Interval \(ms\))|(GC Monitor:Percentage of Time Spent in GC during last 15 minutes)' 

我需要创建一个 for 循环并一次通过一个 metricName。例如,第一个 (WebSpherePMI\|jvmRuntimeModule:ProcessCpuUsage) 然后 (WebSpherePMI\|threadPoolModule\|WebContainer:ActiveCount) 然后 (GC Monitor\|Memory Pools\|Java heap:Percentage of Maximum Capacity Currently Used) 等等。分隔符是 |但不是这个\|

我尝试创建一个数组:

data[] 
 
data.append(metricName.split('|')) 

但它给了我这样的数组:

[['(WebSpherePMI\\', 'jvmRuntimeModule:ProcessCpuUsage)', '(WebSpherePMI\\', 'threadPoolModule\\', 'WebContainer:ActiveCount)', '(GC Monitor\\', 'Memory Pools\\', 'Java heap:Percentage of Maximum Capacity Currently Used)', '(GC Monitor\\', 'Garbage Collectors\\', '(.*):GC Invocations Per Interval Count)', '(GC Monitor\\', 'Garbage Collectors\\', '(.*):GC Time Per Interval \\(ms\\))', '(GC Monitor:Percentage of Time Spent in GC during last 15 minutes)']] 

有什么想法可以将它放入数组中吗?

请您参考如下方法:

您可以使用正则表达式拆分您的字符串:

>>> import re 
>>> re.split(r'(?<=\))\|(?=\()',metricName) 
['(WebSpherePMI\\|jvmRuntimeModule:ProcessCpuUsage)', '(WebSpherePMI\\|threadPoolModule\\|WebContainer:ActiveCount)', '(GC Monitor\\|Memory Pools\\|Java heap:Percentage of Maximum Capacity Currently Used)', '(GC Monitor\\|Garbage Collectors\\|(.*):GC Invocations Per Interval Count)', '(GC Monitor\\|Garbage Collectors\\|(.*):GC Time Per Interval \\(ms\\))', '(GC Monitor:Percentage of Time Spent in GC during last 15 minutes)'] 

在这种情况下 r'(?<=\))\|(?=\()将根据 ) 之间的 pip 符号拆分您的字符串和 ( .它使用 positive look-around为了比赛!