python文件内容解析

帮忙设计一个函数,具体功能是解析文件中的文本

文本文件内容格式类似下面这种:

.myfile  name1  A  +  B
.myfile  name2  A  -  B
.myfile  name3  A  -  B  *  C
.myfile  name4  min(A  B  C)
.myfile  name5  D - max(A  B * C)
.myfile  name6  (D - C) * max(A  B * C)

通过函数能够直接解析为:

name1 tran  result  =  'A + B'
name2 tran  result  =  'A - B'
name3 tran  result  =  A - B *  C
name4 tran  result  = 'min(A B C)'
name5 tran  result  =  'D - max(A  B*C)'
name5 tran  result  =  '(D - C) * max(A  B*C)'

def parse(filePath):
    with open(filePath,'r',encoding='utf8') as file:
        lines = file.readlines()

        for line in lines:
            line = line.split('  ',2)
            print(line[1],'tran','result','=',line[2],end='')

parse(r'file.txt')

这是该功能的可能实现,不一定可以实现您的全部需求,但您可以参考:

def parse_file(file_name: str) -> Dict[str, str]:
    result = {}
    # Open the file in read mode
    with open(file_name, 'r') as file:
        # Read each line in the file
        for line in file:
            # Split the line by whitespace
            line_parts = line.split()
            # Get the name and the expression by using the index
            # of the line_parts list
            name = line_parts[1]
            expression = ' '.join(line_parts[3:])
            # Add the name and the expression to the result dictionary
            result[name] = expression
    # Return the result dictionary
    return result

要使用这个函数,你可以这样调用它:

file_name = 'myfile.txt'
result = parse_file(file_name)
# Print the result
print(result)

这将打印一个包含名称作为键和表达式作为值的字典。

例如,对于问题中给出的输入文件,输出将是:

{
    'name1': 'A + B',
    'name2': 'A - B',
    'name3': 'A - B * C',
    'name4': 'min(A B C)',
    'name5': 'D - max(A B * C)',
    'name6': '(D - C) * max(A B * C)'
}