在包含字符串的文本文件中打印行

时间:2014-11-04 14:29:42

标签: python file-search

我试图获取包含某个字符串的文本文件的行,并在该行中打印第3个数字或字符串。文本文件如下所示:

1997 180 60 bob

1997 145 59 dan

如果输入文字包含bob,我的代码应打印60

这是我到目前为止所拥有的:

calWeight = [line for line in open('user_details.txt') if name in line]
stringCalWeight = str(calWeight)
print (stringCalWeight)

我该如何解决?

3 个答案:

答案 0 :(得分:1)

with open('user_details.txt') as f:
    for line in f:
        if "bob" in line:
            print(line.split()[2]) 

如果你想要bb在行中的所有nums的列表,请使用列表理解:

with open('user_details.txt') as f:
    nums =  [line.split()[2] for line in f if "bob" in line]

在检查是否要避免名称是行中字符串的子字符串的情况之前,您可能还想要拆分,例如bob in bobbing - >真:

 nums =  [line.split()[2] for line in f if "bob" in line.split()]

我认为更有用的结构是dict,其中值是与每个名称关联的行中的所有第三个数字:

from collections import defaultdict
d = defaultdict(list)
with open("in.txt") as f:
    for line in f:
        if line.strip():
           spl = line.rstrip().split()
           d[spl[-1]].append(spl[2])
print(d)
defaultdict(<type 'list'>, {'bob': ['60'], 'dan': ['59']})

答案 1 :(得分:0)

通过re模块。

>>> L = []
>>> for line in open('/home/avinash/Desktop/f'):
        if 'bob' in line:
            L.append(re.search(r'^(?:\D*\d+\b){2}\D*(\d+)', line).group(1))


>>> print(L)
['60']

答案 2 :(得分:0)

#need to open the file properly
with open('info.txt', 'r') as fp:
    #as suggested by @Padraic Cunningham it is better to iterate over the file object
    for line in fp:
        #each piece of information goes in a list
        infos = line.split()
        #this makes sure that there are no problems if your file has a empty line
        #and finds bob in the information
        if infos and infos[-1] == 'bob':
            print (infos[2])