Python行比较

2024-04-25 01:01:40 发布

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

我有一个目录,其子目录中充满了包含以下行的文件:

VERSION "1.0"  # THAT NUMBER VARIES.

因此,作为内容示例的一个文件如下:

 #comments about what the file program does
 #
 #

 #ifndefine _AWS_THIS_READS_STUFF_H
 #define _AWS_THIS_READS_STUFF_H

 #define AWS_THIS_READS_STUFF_VERSION "1.2" <---this is the line I want 
                                            #to compare that is in all

然后文件的读取将是一些用C编写的长程序。你知道吗

我用这个号码来识别我什么时候做了改变。我需要在Python中做一些东西来标识十进制数之前和之后的数字在一个目录中是否都匹配,因为有数百个文件。你知道吗

import glob
import sys
import re
import filecmp
from collections import defaultdict
from itertools import dropwhile

myfiles = glob.glob('*.h')
for filename in myfiles: 
print(filename) #this prints all of the file names

def all_same(patt):
    r = re.compile('#define\s+([_A-Z]+)_VERSION\s+("\d+\.\d+")$') #REGEX to find
    files = glob.glob(patt)
    d = defaultdict(list)
    for file in files:
        with open(file) as f:
            version = r.search(next(dropwhile(lambda x: "VERSION" not in x, f)))
            d[version].append(file) #search for VERSION LINE
return d

当它在我的命令提示符下运行时,它不会输出任何内容。你知道吗

我也试过这个!-我得到它打印出文件和“0.0”的数字,但现在我需要比较!你知道吗

myfiles = glob.glob('*.h') #reads in all files ending in .h
for file in myfiles:
    for line in open(file):
        line = line.rstrip()
        if re.search('VERSION\s+("\d+\.\d+")$', line):
            list = re.findall("\d+\.\d+" , line)
            list.append(file)
            print(list)
            #print (list + ' : ' + root + "/" + myfile)
    with open(file) as f:
        version = re.findall('VERSION\s+("\d+\.\d+")$', file)
        version = re.search(next(dropwhile(lambda x: "VERSION" not in x, f)))
        print(version)

只需找出如何比较“0.0”列表中的数字(同样,小数点前和小数点后)


Tags: 文件inimportreforsearchversionline
1条回答
网友
1楼 · 发布于 2024-04-25 01:01:40

如果您的版本行是每个文件的头,那么您可以提取从iglob返回的第一行,并用all将该行与其余行进行比较:

import glob
import re
from collections import defaultdict
def all_same(patt):
    r = re.compile("VERSION\s+(\d+\.\d+)")
    files = glob.iglob(patt)
    d = defaultdict(list)
    for file in files:
        with open(file) as f:
            version = r.search(next(dropwhile(lambda x: "VERSION" not in x, f)))
            d[version].append(file)
    return d

如果您真的想用不同的版本号来显示所有文件的名称,我会在每个文件中找到版本行,并在dict中按版本号进行分组,使用版本号作为键,并附加文件名作为值:

import glob
import re
from collections import defaultdict
from itertools import dropwhile
def all_same(path):
    r = re.compile("VERSION\s+(\d+\.\d+)")
    files = glob.iglob(path)
    d = defaultdict(list)
    for file in files:
        with open(file) as f:
            version = r.search(next(dropwhile(lambda x: "VERSION" not in x, f))).group()
            d[version].append(file)
    return d

相关问题 更多 >