比较不同的文件并获得共同点

时间:2014-08-04 13:56:51

标签: python list file compare

我有两个这样的txt文件

file1.txt    file2.txt

 a           a propertya
 b           z propertyz
 c           c propertyc
 d           m propertym
 e           f propertyf
 f           w propertyw
 g           e propertye    
 etc         b propertyb
             d propertyd
             x propertyx
             g propertyg
             etc

(file1的所有元素都在file2中,但不是另一种方式,file2包含所有模块,file1只是一组模块)我需要比较这些文件并获得另一个带有共同元素的txt文件相应的财产,我的意思是

file.txt的

a propertya
b propertyb
c propertyc
d propertyd
e propertye
f propertyf
g propertyg

我不知道该怎么做(我是python的新手),我只是可以做一些简单的事情,比如获取共同的对象列表,但我不知道如何编写各自的属性。

3 个答案:

答案 0 :(得分:0)

elements = []
with open('file1.txt') as f:
    for line in f:
        elements.append(line[:line.find('\n')])

newFile = open('file.txt','a')
with open('file2.txt') as f:
    for line in f:
        if elements.__contains__(line[0:1]):
            newFile.write(line)
newFile.close()

答案 1 :(得分:0)

阅读这两个文件;

with open('file1.txt') as f:
    f1 = f.readlines()
f1 = [k.strip() for k in f1]  # Remove unneeded whitespace
letters = ''.join(f1)  # make it into a string of letters
with open('file2.txt') as f:
    f2 = f.readlines()
f2 = [k.strip() for k in f2]  # Remove unneeded whitespace

对于f2中的每一行,检查它是否以第一个文件中的字母开头

lines = [ln for ln in f2 if ln[0] in letters]

将结果写入文件;

with open('file.txt', 'w') as out:
    out.write('\n'.join(lines))

答案 2 :(得分:0)

如果格式与您的示例相同,则fil1.txt似乎具有在file2.txt中定义的字典的键。您可以使用以下脚本将file2.txt加载到dict中:

sep = " "
d = {}
with open("file2.txt", "r") as fd:
    for line in fd:
        # strip() to get rid of unnecesary spaces/endline/etc
        key, val = line.strip().split(sep)
        d[key] = val

现在您可以阅读file1.txt并从那里获取密钥,使用以下代码:

with open("file1.txt", "r") as fd:
    keys = fd.readlines()
keys = [k.strip() for k in keys]
for k in keys:
    print "%s %s" % (k, dict[k])

一些意见:

  • sep是一个容纳sepparator的变量。通常这是一个','char,在你的情况下它似乎是一个空间'',但这往往会带来问题。如果逗号也有问题,您可以使用管道“|”,或者任何奇怪的字符都不应该出现在您的数据中。如果您需要其他sepparator,则必须更新文件。
  • 打印属性的顺序取决于file1.txt。
  • 的顺序
  • 我做了一个简单的打印,可以根据您的需要进行改进。

编辑:修正了一些拼写错误。

相关问题