Python 如何根据项目中的数字拆分列表项目

Python 如何根据项目中的数字拆分列表项目,python,regex,split,Python,Regex,Split,我目前正在解析这个巨大的rpt文件。在每个项目中,括号中都有一个值。例如,项目编号为3.14。如何使用python中的split函数提取3.14?还是有别的办法 #Splits all items by comma items = line.split(',') #splits items within comma, just gives name name_only = [i.split('_')[0] for i in items] # print(name_only) #splits

我目前正在解析这个巨大的rpt文件。在每个项目中,括号中都有一个值。例如,项目编号为3.14。如何使用python中的split函数提取3.14?还是有别的办法

#Splits all items by comma
items = line.split(',')

#splits items within comma, just gives name
name_only = [i.split('_')[0] for i in items]
# print(name_only)

#splits items within comma, just gives full name
full_name= [i.split('(')[0] for i in items]
# print(full_Name)

#splits items within comma, just gives value in parentheses
parenth_value = [i.split('0-9')[0] for i in items]
# parenth_value = [int(s) for s in items.split() if s.isdigit()]
print(parenth_value)

parenth_value = [i.split('0-9')[0] for i in items]

对于从字符串中提取数字的更一般的方法,您应该阅读有关正则表达式的内容

对于这种非常特殊的情况,您可以先按分割,然后按分割,以获得它们之间的值

像这样:

行=项目编号3.14 num=行。拆分[1]。拆分[0] printnum
您可以简单地找到括号和结束括号的起始索引,并获得它们之间的区域:

start_paren = line.index('(')
end_paren = line.index(')')
item = line[start_paren + 1:end_paren]
# item = '3.14'
或者,您可以使用regex,它提供了一个可以说更优雅的解决方案:

import re
...
# anything can come before the parentheses, anything can come afterwards.
# We have to escape the parentheses and put a group inside them
#  (this is notated with its own parentheses inside the pair that is escaped)
item = re.match(r'.*\(([0-9.-]*)\).*', line).group(1)
# item = '3.14'

可以使用正则表达式并执行以下操作

import re
sentence = "item_number_one(3.14)"
re.findall(r'\d.+', sentence)

可以使用以下正则表达式获取整数值:

import re

text = 'item_number_one(3.14)'

re.findall(r'\d.\d+', text)

o/p: ['3.14']
说明:

\d-匹配任何十进制数字;这相当于类[0-9]

+-一个或多个整数


同样,您可以解析rpt文件,拆分行并获取括号中的值。

那么为什么要用逗号拆分呢?请给出。您可能会想出一种使用括号拆分的方法,但在这种情况下正则表达式会更容易。我认为您可以使用以下模式:?因为您使用的是RPT,这个答案可能会有所帮助:因此您不必手动拆分行。您也可以尝试。这通常意味着,你需要的是与当地导师一起度过的时间,或是浏览教程,而不是堆栈溢出。您发布的代码几乎没有试图解决给定的问题。