在 python 中的另一个文件的行中查找模式
Find a pattern in the line of another file in python
我正在学习 python 所以我有两个包含很多行的文件:
文件 1
71528
1452
14587
文件 2
country_hoj_17458 9 CA 5 CA 78.4
country_hoj_1452 10 CA 15 CA 96.5
country_hoj_14787 19 CA 51 CA 12.4
country_hoj_15742 19 CA 51 CA 12.4
country_hoj_171528 19 CA 51 CA 12.4
我想打印第一列中模式(数字)文件 1 与文件 2 匹配的行。我想要这样的输出文件
country_hoj_1452 10 CA 15 CA 96.5
country_hoj_14787 19 CA 51 CA 12.4
我的脚本是这样的:
filename = numbers.txt
filename2 = data.txt
with open(filename) as f:
with open (filename2) as m:
for line in f:
if line in m:
print (m)
我需要在其中修复什么?任何人都可以帮助我并支持我吗?非常感谢
filename = 'numbers.txt'
filename2 = 'data.txt'
with open(filename) as numberLines:
with open (filename2) as dataLines:
nL = numberLines.read().splitlines()
dL = dataLines.read().splitlines()
dataReadLines = [j for i in nL for j in dL if i in j]
#dataReadLines = [i for i in nL]
print (str(dataReadLines))
另一个答案,其中每个键都与它们各自的数据查找配对。我已经更改了您的输入,您可以使用以下代码轻松理解。
from collections import defaultdict
filename = 'numbers.txt'
filename2 = 'data.txt'
with open(filename) as numberLines:
with open (filename2) as dataLines:
nL = numberLines.read().splitlines()
dL = dataLines.read().splitlines()
defDList = defaultdict(list)
dataReadLines = [defDList[i].append(j) for i in nL for j in dL if i in j]
#dataReadLines = [i for i in nL]
print (defDList)
我正在学习 python 所以我有两个包含很多行的文件:
文件 1
71528
1452
14587
文件 2
country_hoj_17458 9 CA 5 CA 78.4
country_hoj_1452 10 CA 15 CA 96.5
country_hoj_14787 19 CA 51 CA 12.4
country_hoj_15742 19 CA 51 CA 12.4
country_hoj_171528 19 CA 51 CA 12.4
我想打印第一列中模式(数字)文件 1 与文件 2 匹配的行。我想要这样的输出文件
country_hoj_1452 10 CA 15 CA 96.5
country_hoj_14787 19 CA 51 CA 12.4
我的脚本是这样的:
filename = numbers.txt
filename2 = data.txt
with open(filename) as f:
with open (filename2) as m:
for line in f:
if line in m:
print (m)
我需要在其中修复什么?任何人都可以帮助我并支持我吗?非常感谢
filename = 'numbers.txt'
filename2 = 'data.txt'
with open(filename) as numberLines:
with open (filename2) as dataLines:
nL = numberLines.read().splitlines()
dL = dataLines.read().splitlines()
dataReadLines = [j for i in nL for j in dL if i in j]
#dataReadLines = [i for i in nL]
print (str(dataReadLines))
另一个答案,其中每个键都与它们各自的数据查找配对。我已经更改了您的输入,您可以使用以下代码轻松理解。
from collections import defaultdict
filename = 'numbers.txt'
filename2 = 'data.txt'
with open(filename) as numberLines:
with open (filename2) as dataLines:
nL = numberLines.read().splitlines()
dL = dataLines.read().splitlines()
defDList = defaultdict(list)
dataReadLines = [defDList[i].append(j) for i in nL for j in dL if i in j]
#dataReadLines = [i for i in nL]
print (defDList)