繁体   English   中英

如何同时读取多个输入(文本)文件并进行一些计算后再次打印?

[英]How to read from multiple input (text) files at the same time and print it again after doing some calculation?

我有两个不同字典(单独的txt文件)的两个输入,我想逐行读取两个文件,比较并在txt文件中打印结果。 (循环)我的两个输入看起来像这样

eshark 
white 
shark
shark
carcharodon
carcharias

etench
tinca 
goldfish 
carassius 
auratus
great

我试过了

with open('file1.txt', 'r') as f1: # for the first file 
data = f1.read()

with open('file2.txt', 'r') as f2:
data1 = f2.read() 
output = data == data1   # output is 1(true) or 0 (false)    
with open("Output1.txt", "w") as text_file 
text_file.write("word: %s :%s :%f" % (data ,data1 , output ))

我也尝试过,但是同样的问题

with open('file1.txt') as f1,open('file2.txt') as f2:

当我的数据来自一个文件时,我得到了正确的输出,但是当我尝试使用这两个文件时,我得到了以下输出:

word:shark 
white 
shark
shark
carcharodon
carcharias
:shark 

同时,我想要这个输出

word:etench : 0
word:white : tinca : 0
word:shark : goldfish  : 0 
word:shark : carassius : 0 
word:carcharodon : auratus : 0
word:carcharias : great : 0 

您可以使用readlines将文件读入列表,然后进行迭代以进行比较:

with open('file1.txt', 'r') as f:
    data1 = f.readlines()
with open('file2.txt', 'r') as f:
    data2 = f.readlines()
data = zip(data1, data2)
with open('output.txt', 'a') as f:
    for x in data:
        out = '{} : {} : {}\n'.format(x[0].strip(), x[1].strip(), x[0] == x[1])
        f.write(out)

这可能是您的问题的答案:

with open("file1", 'r') as f1, open("file2", 'r') as f2:
    j= 0
    data2 = [k.strip("\n").strip() for k in f2.readlines()]
    for line in f1:
        if j == len(data2):
            break
        if line.strip("\n").strip() == data2[j:j+1][0]:
            output = "word:{0}:{1} = {2}".format(line.strip("\n").strip(), data2[j:j+1][0], 1)
        else:
            output = "word:{0}:{1} = {2}".format(line.strip("\n").strip(), data2[j:j+1][0], 0)
        j += 1

        with open("output_file", 'a') as out:
            out.write(output + "\n")

输出:

word:eshark:etench = 0
word:white:tinca = 0
word:shark:goldfish = 0
word:shark:carassius = 0
word:carcharodon:auratus = 0
word:carcharias:great = 0

您基本上就在那里。 读完数据后,就需要遍历每行。 目前您还不是。 您可以使用zip将来自不同文件的行配对在一起。

我个人会使用生成器(因为我喜欢生成器),但这不是必需的。

def read_lines(file_path):
    with open(file_path, 'r') as fh:
        for line in fh:
            yield line

data1 = read_lines(r"/Documents/file1.txt")
data2 = read_lines(r"/Documents/file2.txt")
data = zip(data1, data2)

with open(r"/Documents/output.txt", 'w') as fh:
    for left, right in data:
        equal = left == right
        line = "word:{left}: {right}: {equal}\n".format(left=left.strip(), 
                                                        right=right.strip(), 
                                                        equal=equal)
        fh.write(line)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM