在字典中查找表达式和常用关键字

2024-06-02 06:52:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从一个文件中解析变量及其所在的时间间隔。例如,输入文件可能包含以下内容:

常数

 x1 = 1;   

变数

x45 in [-45,5844];

x63 in [0,456];

x41 in [45, 1.e8]; #Where 1.e8 stands for 10^8

我所要做的就是把每一对(变量、间隔)存储在字典中。如果它是常数,那么间隔就是[常数,常数]。我首先想象我必须使用内置函数findall在整个文件中搜索“random_interval”或“x”random_number=random_number”中类型为“x”random_number“的所有行,但我不知道在找到我想要的所有行之后如何获取和存储“x”和间隔

此外,每当间隔中有“1.e8”时,我想在将其存储在字典中之前,将其替换为“10^8”

有线索吗

谢谢你帮我解决问题


Tags: 文件innumber间隔字典时间常数random
2条回答

老实说,我不知道该怎么开始。我所做的就是:

from sys import argv
import re

script, filename = argv
#The file which contains the variables is filename, so that I can use as a command 
in a terminal : "python myscript.py filename.txt"

file_data = open(filename, 'r')
Dict = {} #The dictionnary in which I want to store the variables and the intervals
txt = file_data.read()  

#Here I thought I might use this : re.findall(.*"in".*, txt) or something like that 
#but It will get me all the lines of the type "blabla in bloblo".
#I want also blabla and bloblo so that I can put them into my dictionnary like this : 
#Dict[blabla] = bloblo
#In the dictionnary it will be for example Dict = {x45 : [-10, 456]}

file_data.close()

回答Akilan

如果文件是以下文件:

Constants
x1 = 5;

Variables
x56 in [3,12];
x78 in [1,4];

它应返回以下内容:

{"x1" : [5,5], "x56" : [3,12], "x78" : [1,4]}

相关问题 更多 >