gpt4 book ai didi

python - 在 Python 中有效地比较两个文件中的行

转载 作者:行者123 更新时间:2023-12-04 07:49:52 27 4
gpt4 key购买 nike

我正在尝试比较两条线并捕获彼此匹配的线。例如,
file1.txt 包含

my
sure
file2.txt 包含
my : 2
mine : 5
sure : 1
我正在尝试输出
my : 2
sure : 1
到目前为止,我有以下代码
inFile = "file1.txt"
dicts = "file2.txt"


with open(inFile) as f:
content = f.readlines()

content = [x.strip() for x in content]

with open(dicts) as fd:
inDict = fd.readlines()

inDict = [x.strip() for x in inDict]

ordered_dict = {}

for line in inDict:
key = line.split(":")[0].strip()
value = int(line.split(":")[1].strip())
ordered_dict[key] = value

for (key, val) in ordered_dict.items():
for entry in content:
if entry == content:
print(key, val)
else:
continue
然而,这是非常低效的,因为它循环了两次并且迭代了很多次。因此,这对于大文件来说并不理想。我怎样才能使它适用于大文件?

最佳答案

您不需要嵌套循环。一个循环读取 file2 并转换为 dict,另一个循环读取 file1 并查找结果。

inFile = "file1.txt"
dicts = "file2.txt"

ordered_dict = {}
with open(dicts) as fd:
for line in fd:
a,b = line.split(' : ')
ordered_dict[a] = b

with open(inFile) as f:
for line in f:
line = line.strip()
if line in ordered_dict:
print( line, ":", ordered_dict[line] )
第一个循环可以作为列表理解来完成。
with open(dicts) as fd:
ordered_dict = dict( line.strip().split(' : ') for line in fd )

关于python - 在 Python 中有效地比较两个文件中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67039978/

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