gpt4 book ai didi

python - 处理文本文件的通用算法/模式

转载 作者:太空宇宙 更新时间:2023-11-04 01:36:38 25 4
gpt4 key购买 nike

是否有读取多行文本文件的通用算法/模式,其中某些行依赖于前面的行?我指的是以下形式的数据:

H0 //start header
HEADER1
H9 //end header
R0 RECORD1
R0 RECORD2
H0 //start header
HEADER2
H9 //end header
R0 RECORD3
R0 RECORD4

需要将当前“标题”信息与每个后续记录相关联的地方。

我知道这类任务有无数的解决方案,但是是否有经验丰富的开发人员会集中使用的久经考验的模式?

编辑:我的直觉是应该使用某种状态机,其中包含“阅读标题”、“阅读记录”等状态。我走的路对吗?

编辑:虽然例子很简单,但是能处理更高层次嵌套的东西会更可取

最佳答案

这可以看作是一个解析问题,尽管该语言的语法非常简单。确实是regular ,因此正如您正确指出的那样,FSM 将起作用。一般来说,任何已建立的解析技术都可以工作;如果使用 recursive descent parsing,您将避免显式状态,在常规语言的情况下它变得不是真正的递归。以下为伪代码:

function accept_file:
while not_eof
read_line;
case prefix of
"H0": accept_header;
"R0": accept_record;
otherwise: syntax_error;

function accept_record:
make_record from substring of current_line from position 3;

function accept_header:
read_line;
while current_line does not start with "H9"
add line to accumulated_lines
create header from accumulated_lines

关于python - 处理文本文件的通用算法/模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9148699/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com