python - 使用正则表达式逐行搜索纯文本文件,并根据匹配挑选行

标签 python regex format

我正在尝试逐行读取纯文本文件,挑选以任意六位数字的模式开头的行。将它们传递到列表,然后将该列表逐行写入 .csv 文件。

这是我尝试在文件中匹配的行的示例:

**000003**  ANW2248_08_DESOLATE-WASTELAND-3. A9    C        00:55:25:17 00:55:47:12 10:00:00:00 10:00:21:20

这里是两个图像的链接,其中一个显示了文件其余部分上下文中的上述行以及预期结果:/image/m10YH.jpg

import csv
identifier = re.compile(r'^(\d\d\d\d\d\d)')

matched_line = []
with open('file.edl', 'r') as file:
    reader = csv.reader(file)
    for line in reader:
        line = str(line)
        if identifier.search(line) == True:
            matched_line.append(line)
        else: continue

with open('file.csv', 'w') as outputEDL:
    print('Copying EDL contents into .csv file for reformatting...')
    outputEDL.write(str(matched_line))

预期结果是读者到达一行,使用正则表达式进行搜索,然后如果搜索结果在开头找到一系列 6 个数字,则会将该整行附加到 matches_line 列表中。

我实际上得到的是,一旦我将阅读器读取的内容写入 .csv 文件,它只会挑选出 [],因此正则表达式搜索显然无法按照我编写的方式正常运行代码。任何有关如何更好地形成它以实现我想要做的事情的提示将不胜感激。

谢谢。

最佳答案

更多预期输入/输出的示例将更好地帮助解决此问题,但从我所看到的情况来看,您正在尝试在包含 csv 时间戳的文本文件中写入每一行。在这种情况下,这里有一些伪代码可以帮助您解决问题,还有一个单独的正则表达式匹配函数可以使您的代码更具可读性


    import re
    def match_time(line):
        pattern = re.compile(r'(?:\d+[:]\d+[:]\d+[:]\d+)+')
        result = pattern.findall(line)
        return " ".join(result)

如果找到匹配,这将返回整个时间码的字符串


    lines = []
    with open('yourfile', 'r') as txtfile:
        with open('yourfile', 'w') as csvfile:
            for line in txtfile:
                res = match_line(line)
                #alternatively you can test if res in line which might be better
                if res != "":
                   lines.append(line)
            for item in lines:
                csvfile.write(line)

打开文本文件进行读取,如果该行包含时间码,则将该行附加到列表中,然后迭代该列表并将该行写入 csv。

关于python - 使用正则表达式逐行搜索纯文本文件,并根据匹配挑选行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57411123/

相关文章:

C : apply formatting (right align, center等)到终端文本输出

PHP 正则表达式替换

regex - 使用 PowerShell 从文本段落中提取 6 位数字字符串导致空白数据

javascript - 正则表达式提取模式之间的文本

python - 正则表达式的不平衡括号错误

javascript - 动态文本格式

go - "%!s"- 当格式字符串来自参数时 fmt.Printf 中出现类似错误(go 语言)

python - Python中genfromtxt()中的可变列数?

用于创建音乐播放列表的 Python 模块 (windows)

Python/Kivy - 替换调用函数的另一个屏幕中的标签值