gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 22:45:01 25 4
gpt4 key购买 nike

我有来自两个不同词典(单独的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)

关于python - 如何同时读取多个输入(文本)文件并在进行一些计算后再次打印?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41316270/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com