我正在try 判断输入文件中的字符串,并使用re来合成模式和解析的输入文件.在这里,输入的是CSV文件与多行的SQL类似的脚本,我想要验证字符串的顺序,首先判断关键字1,然后判断ketword2,然后判断关键字3在输入的CSV文件的每一行.通过这样做,我使用了for循环,但我觉得肯定有更好的方法来处理这个问题.有没有人建议如何处理这件事?

use case

CREATE application vat4_xyz_rcc_clm1_trm_soc WITH some text
CREATE flow flow_src_vat4_xyz_rcc_clm1_trm_soc some text
CREATE stream main_stream_vat4_xyz_rcc_clm1_trm_soc with some text
CREATE OR REPLACE target comp_tgt_vat4_xyz_rcc_clm1_trm_soc some text

为了处理这个问题,我try 了以下方法:

kword=['CREATE','CREATE OR REPLACE']
    with open('myinput.txt', 'r+') as f:
        lines = f.readlines()
        nlines = [v for v in lines if not v.isspace()]
        for line in nlines:
            for string in line:
                for word in kword:
                    if string is word:
                        atype=next(string)
                        print('type is', atype)  # such as application, flow, stream
                        
                        if atype in ['application', 'flow', 'steam']:
                            value=next(atype)  ## such as vat4_xyz_rcc_clm1_trm_soc, flow_src_vat4_xyz_rcc_clm1_trm_soc
                            print("name", value)
                        else:
                            print("name not found")
                    else:
                        print("type is not correct")

但这样做并不是高效的代码.我认为re可能会在这里做得很好.有人对此有更好的 idea 吗?

objective:

基本上,我需要分析每一行,如果我发现关键字1,如CREATE,则判断ketword1旁边的单词,如果NextWord为application,则打印此行并判断它的下一个单词,我在其中合成了模式,如下所示:

vat4_xyz_rcc_clm1_trm_soc
pat1=r'^[\vat\d+]_(?:xyz|abs)_rcc_[clm\d+]_trm_(?:soc|aws)'
m=re.match(pat1, curStr, re.M)

下面是每条线具有不同模式情况,例如

pat1=r'^[\vat\d+]_(?:xyz|abs)_rcc_[clm\d+]_trm_(?:soc|aws)'
pat2=r'^\flow_src_[\vat\d+]_(?:xyz|abs)_rcc_[clm\d+]_trm_(?:soc|aws)'
pat3=r'^\main_stream_[\vat\d+]_(?:xyz|abs)_rcc_[clm\d+]_trm_(?:soc|aws)'
pat4=r'^\comp_tgt_[\vat\d+]_(?:xyz|abs)_rcc_[clm\d+]_trm_(?:soc|aws)'

我们如何才能使解析每行re行的操作变得简单?有什么 idea 吗?

推荐答案

正则表达式似乎可以比您try 的简单得多.不如这样吧:

import re

matcher = re.compile(r"^(CREATE(?: OR REPLACE)?) (\S+) (\S+).*$")

with open("test.txt", "r") as f:
    for line in f:
        if match := matcher.match(line):
            action, action_type, value = match.groups()
            print(f"{action=}, {action_type=}, {value=}")

输出:

action='CREATE', action_type='application', value='vat4_xyz_rcc_clm1_trm_soc'
action='CREATE', action_type='flow', value='flow_src_vat4_xyz_rcc_clm1_trm_soc'
action='CREATE', action_type='stream', value='main_stream_vat4_xyz_rcc_clm1_trm_soc'
action='CREATE OR REPLACE', action_type='target', value='comp_tgt_vat4_xyz_rcc_clm1_trm_soc'

如果您想进一步验证值,我将获取第一个正则表达式的结果,并将它们输送到针对每种情况的更专用的正则表达式中.

import re

line_matcher = re.compile(r"^(CREATE(?: OR REPLACE)?) (\S+) (\S+).*$")
value_matchers = {
    "application": re.compile(r'^vat\d+_(xyz|abs)_rcc_clm\d+_trm_(soc|aws)'),
    "flow": re.compile(r'^flow_src_vat\d+_(xyz|abs)_rcc_clm\d+_trm_(soc|aws)'),
    "stream": re.compile(r'^main_stream_vat\d+_(xyz|abs)_rcc_clm\d+_trm_(soc|aws)'),
    "target": re.compile(r'^comp_tgt_vat\d+_(xyz|abs)_rcc_clm\d+_trm_(soc|aws)'),
}

with open("test.txt", "r") as file:
    for line in file:
        if not (line_match := line_matcher.match(line)):
            print(f"Invalid line: {line=}")
            continue

        action, action_type, value = line_match.groups()
        if not (value_matcher := value_matchers.get(action_type)):
            print(f"Invalid action type: {line=}")
            continue

        if not value_matcher.match(value):
            print(f"Invalid {action_type} value: {line=}")
            continue

        # Do some work on the items
        ...

Python相关问答推荐

使用from_pandas将GeDataFrame转换为polars失败,ArrowType错误:未传递numpy. dype对象

Pandas 除以一列中出现的每个值

计算所有前面行(当前行)中列的值

在Python和matlab中显示不同 colored颜色 的图像

如何在Deliveryter笔记本中从同步上下文正确地安排和等待Delivercio代码中的结果?

如何使用pandasDataFrames和scipy高度优化相关性计算

Gekko:Spring-Mass系统的参数识别

可变参数数量的重载类型(args或kwargs)

Python虚拟环境的轻量级使用

Pandas DataFrame中行之间的差异

Python逻辑操作作为Pandas中的条件

如何从需要点击/切换的网页中提取表格?

使用Python查找、替换和调整PDF中的图像'

Polars将相同的自定义函数应用于组中的多个列,

将一个双框爆炸到另一个双框的范围内

统计numpy. ndarray中的项目列表出现次数的最快方法

在极点中读取、扫描和接收有什么不同?

极点用特定值替换前n行

递归链表反转与打印语句挂起

两个名称相同但值不同的 Select 都会产生相同的值(discord.py)