鱼C论坛

 找回密码
 立即注册
查看: 1523|回复: 6

请问如何找出两个txt文件的相同行?

[复制链接]
发表于 2019-3-24 21:24:13 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
=====================
第一个文件的内容是:
000001 刘晓晓
098873 高峰冯
600335 王静
第二个文件的内容是:
王静
高峰
======================
我想要对比两个文件中的每一行,找出第二个文件和第一个名字相同的行,并打印出来,代码是:
  1. for j in f2:
  2.     for i in f1:
  3.         if j[0] == i[7]:
  4.             print(i)
复制代码

结果打印出来啥也没有,请问该怎么改呢?
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2019-3-24 21:32:19 | 显示全部楼层
       可是,这两个文件确实没有内容完全相同的行啊,你到底想干什么?
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 1 反对 0

使用道具 举报

发表于 2019-3-24 21:37:46 | 显示全部楼层
f1 = open("1.txt", "r")
f2 = open("2.txt", "r")
txt1 = f1.readlines()
txt2 = f2.readlines()

i = 0
for str1 in txt1:
    for str2 in txt2:
        if(str2 in str1):
            print(str2)

f1.close()
f2.close()
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-3-24 21:40:19 | 显示全部楼层

  1. f1=[]
  2. f2=[]
  3. with open(r"1.txt","r") as f:
  4.         for line in f:
  5.                 line = line.strip('\n')
  6.                 line = line.split(' ')[1]
  7.                 f1.append(line)
  8.                
  9. with open(r"2.txt","r") as f:
  10.         txt = f.read()
  11.         f2 = txt.splitlines()

  12. for e1 in f1:
  13.         if e1 in f2:
  14.                 print('Yes')
  15.                 break
  16. else:
  17.         print('no')
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-3-24 21:41:59 | 显示全部楼层
  1. with open('f1.txt') as f1:
  2.     with open('f2.txt') as f2:
  3.         file1 = f1.readlines()
  4.         file2 = f2.readlines()
  5.         for i in file1:
  6.             for j in file2:
  7.                 if (i.strip('\n') in j) or (j.strip('\n') in i):
  8.                     print(i)
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-3-25 09:45:24 | 显示全部楼层
你去判断第二个文件的内容是否在第一个文件内即可。如:'王静' in '第一个文件的行内容',在就输出。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-3-25 20:08:23 | 显示全部楼层
本帖最后由 13572044595 于 2019-3-25 20:28 编辑
  1. a = []
  2. b = []
  3. with open('1.txt') as f1:
  4.     with open('2.txt') as f2:
  5.         for i in f1:
  6.             i = i.strip('\n')
  7.             a.append(i)
  8.         for j in f2:
  9.             j = j.strip('\n')
  10.             b.append(j)
  11.         for k in a:
  12.             for l in b:
  13.                 if k[7:] == l:
  14.                     print(k)
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2026-1-14 19:25

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表