在文本文件中重复提取特定字符之间的子字符串 (python)
Repeatedly extracting substring inbetween specific characters, in a text file (python)
我有几条数据存储在一个文本文件中。我试图将每种类型的数据提取到单独的列表中,以便我可以绘制 them/make 各种数字。有数以千计的值,所以专门这样做并不是一个真正的选择。
文本文件的示例是:
"G4WT7 > interaction in material = MATERIAL
G4WT7 > process PROCESSTYPE
G4WT7 > at position [um] = (x,y,z)
G4WT7 > with energy [keV] = 0.016
G4WT7 > track ID and parent ID = ,a,b
G4WT7 > with mom dir = (x,y,z)
G4WT7 > number of secondaries= c
G4WT1 > interaction in material = MATERIAL
G4WT1 > process PROCESSTYPE
G4WT1 > at position [um] = (x,y,z)
G4WT1 > with energy [keV] = 0.032
G4WT1 > track ID and parent ID = ,a,b
G4WT1 > with mom dir = (x,y,z)
G4WT1 > number of secondaries= c"
我想提取字符串,例如“energy [keV] =" so 0.016, 0.032 等之后的字符串到列表中。我希望能像这样把所有的数据分开。
到目前为止,我已经尝试使用正则表达式,如下所示:
import re
file = open('file.txt')
textfile =file.read()
Energy = re.findall('[keV] = ;(.*)G', textfile)
但它只是生成一个空列表; []
我是 python 的新手,如果答案很明显,我深表歉意,我们将不胜感激。
您可能想要转义方括号!
Energy = re.findall('\[keV\] = (.*)', text)
... 或者为了保存,您还可以使用 re.escape
来确保所有字符都正确转义,例如:
Energy = re.findall(re.escape('[keV] = ') + '(.*)', text)
我有几条数据存储在一个文本文件中。我试图将每种类型的数据提取到单独的列表中,以便我可以绘制 them/make 各种数字。有数以千计的值,所以专门这样做并不是一个真正的选择。 文本文件的示例是:
"G4WT7 > interaction in material = MATERIAL
G4WT7 > process PROCESSTYPE
G4WT7 > at position [um] = (x,y,z)
G4WT7 > with energy [keV] = 0.016
G4WT7 > track ID and parent ID = ,a,b
G4WT7 > with mom dir = (x,y,z)
G4WT7 > number of secondaries= c
G4WT1 > interaction in material = MATERIAL
G4WT1 > process PROCESSTYPE
G4WT1 > at position [um] = (x,y,z)
G4WT1 > with energy [keV] = 0.032
G4WT1 > track ID and parent ID = ,a,b
G4WT1 > with mom dir = (x,y,z)
G4WT1 > number of secondaries= c"
我想提取字符串,例如“energy [keV] =" so 0.016, 0.032 等之后的字符串到列表中。我希望能像这样把所有的数据分开。
到目前为止,我已经尝试使用正则表达式,如下所示:
import re
file = open('file.txt')
textfile =file.read()
Energy = re.findall('[keV] = ;(.*)G', textfile)
但它只是生成一个空列表; [] 我是 python 的新手,如果答案很明显,我深表歉意,我们将不胜感激。
您可能想要转义方括号!
Energy = re.findall('\[keV\] = (.*)', text)
... 或者为了保存,您还可以使用 re.escape
来确保所有字符都正确转义,例如:
Energy = re.findall(re.escape('[keV] = ') + '(.*)', text)