题目描述
已有两个文件a.dat和b.dat,每个文件都包含若干行句子,现在需要你编写python程序,来找到两个文件中相同的句子,完成以下任务:
1 将相同的句子打印到common.dat文件中,每行一句
2 在控制台打印出程序执行的时长,和相同句子的数量
题目分析
该题目为一个简单的匹配问题,因此最直接的想法是读入两个文件中的所有句子,然后经过简单的处理,利用循环判断哪个句子出现在两个文件中,输入打印该句子,再设定一个计数器进行计数即可,耗时约为2分钟,较慢。
Version1. 利用循环判别
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
def SearchCommonSentences(File1, File2, OutFile):
# import time package
import datetime
begin = datetime.datetime.now()
# Read the two files
File1_Content = open(File1, 'r').readlines()
File2_Content = open(File2, 'r').readlines()
# Count
count = 0
# Output
Out = open(OutFile, 'w')
# Compare One to One
for line1 in File1_Content:
if line1 in File2_Content:
Out.write(line1)
count = count + 1
end = datetime.datetime.now()
print('The running time is:', str(end-begin))
print('The number of common sentences: ', str(count))
Out.close()
# Main
File1 = 'Path/To/File/a.dat';
File2 = 'Path/To/File/a.dat';
OutFile = 'Path/To/File/common1.cat'
SearchCommonSentences(File1, File2, OutFile)
Version1 运行结果
改进 Version2: 基于Set类型
python中有一种数据类型为set类型,set为一种可哈希的数据类型,与字典类似,利用该数据类型可以分别建立两个文件的句子集合,然后利用集合取交集的方式来寻找相同句子,此方法速度很快,耗时约为100毫秒。
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
def SearchCommonSentences(File1, File2, OutFile):
# import time package
import datetime
begin = datetime.datetime.now()
# Read the two files
File1_Connection = open(File1, 'r').readlines()
File2_Connection = open(File2, 'r').readlines()
# For loop 1
Set1 = set()
for line1 in File1_Connection:
Set1.add(line1)
# For loop2
Set2 = set()
for line2 in File2_Connection:
Set2.add(line2)
# Joint
Set3 = Set1 & Set2
# Count
count = len(Set3)
# Output
Out = open(OutFile, 'w')
# Output
for line3 in Set3:
Out.write(line3)
end = datetime.datetime.now()
print('The running time is:', str(end-begin))
print('The number of common sentences: ', str(count))
Out.close()
# Main
File1 = 'Path/To/File/a.dat';
File2 = 'Path/To/File/a.dat';
OutFile = 'Path/To/File/common1.cat'
SearchCommonSentences(File1, File2, OutFile)