0

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

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)

我该如何解决?

4

3 回答 3

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

如果您想要 bob 所在行中的所有 nums 的列表,请使用列表推导:

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

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

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

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

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']})
于 2014-11-04T14:36:50.137 回答
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']
于 2014-11-04T14:39:12.707 回答
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])
于 2014-11-04T14:40:13.173 回答