如何使用通用名称比较两个文本文件的值?

时间:2014-04-03 17:33:54

标签: python python-2.7 text

我正在尝试编写一个python脚本,它将使用公共ID比较两个文本文件中的特定列条目。

我有一个文本文件,其中包含道路名称,起始里程和结束里程。

名称开始结束

0045 0 45

0190 0 3

0006 0 190

第二个文本文件包含许多列,其中三列是我感兴趣的。名称将重复多次,我想将每个名称的每个实例与另一个文本文件中的相应里程进行比较。这些不会基于姓名或英里的任何顺序。

姓名英里

0045 0.05

0045 1.0

0045 5.3

0006 74.6

0006 32.1

我想检查txt2中的Mile是否大于txt1的Begin,但是使用匹配的Names小于来自txt2的End。来自txt2的不在Begin(txt1)和End(txt1)之间的任何行应该写入由脚本创建的第三个文本文件。我知道如何编写IF语句和读/写文本文件,但我真的坚持如何使它与名称匹配,然后比较特定的列。

非常感谢任何帮助!

3 个答案:

答案 0 :(得分:0)

您可以将两个文件中的数据存储在由您的"名称"键入的字典中。参数。然后,您可以使用这些名称访问每个字典中的相应元素。

下面的代码只是一个粗略的指南,我还没有尝试过,它几乎肯定有错误:

d1 = {}  # we are going to put all our file 1 data into a dict.
with open("file1")  as f: # open file 1
    for line in f:        # read each line
        key, begin, end = f.split() # this only works if there are ALWAYS three columns.
        d1[key] = (begin, end)     
#  file1 automatically closes after the "with" block

# same for file 2
d2 = {}
with open("file2")  as f:
    for line in f:       
        key, mile = f.split() 
        d2[key] = mile


common_keys = set(d1.keys()) & set(d2.keys())

# Here we are going to ignore all keys that are not in both
# datasets, but you can use other set operations to work with those entries.

# iterate through the common keys and fish the records out of the dictionaries.
for key in common_keys:
    begin, end = d1[key]
    mile = d2[key]

    ... now do any calculation you like with `mile`, `begin` and `end`.

答案 1 :(得分:0)

这是你需要做的。

我们的想法是将第一个文件读入defaultdictname作为关键字,(begin, end)对列表作为值。然后,在读取第二个文件时,对于每一行,将里程值与我们之前创建的defaultdict中的名称的开始值和结束值进行比较。然后,如果mile值不在beginend之间,请将其写入output.txt

from collections import defaultdict


data = defaultdict(list)
with open('input1.txt', 'r') as f:
    next(f)  # skip first line
    for line in f:
        line = line.strip()
        if line:
            items = line.split()
            data[items[0]].append(map(float, items[1:]))

with open('input2.txt', 'r') as f:
    with open('output.txt', 'w') as output_file:
        next(f)  # skip first line
        for line in f:
            line = line.strip()
            if line:
                name, mile = line.split()
                mile = float(mile)
                for begin, end in data.get(name, []):
                    if not (begin <= mile <= end):
                        output_file.write(line + '\n')

示例:

input1.txt

Name Begin End

0045 0 45

0190 0 3

0006 0 190

input2.txt(请参阅00450006部分beginend范围之外的值:

Name Mile

0045 0.05

0045 1000

0045 5.3

0006 3000

0006 32.1

该脚本生成output.txt

0045 1000
0006 3000

希望有所帮助。

答案 2 :(得分:0)

这是用于在两个文本文件中获取公共号码的程序

from sys import argv

script, filename1, filename2 = argv

txt1 = open(filename1, 'r')
txt2 = open(filename2, 'r')

r = []

for line in txt1.readlines():
    r.append(int(line.rstrip("\n")))

for l in txt2.readlines():
    if int(l.rstrip("\n")) in r:
        print l

打开cmd提示符,转到存储三个文件的位置并键入

  
    
      

python“.py file”filename1 filename2