簡體   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