简体   繁体   中英

Printing the line in a text file that contains a string

I'm trying to get the line of a text file that contains a certain string and printing the 3rd number or string in the line. The text file looks like:

1997 180 60 bob

1997 145 59 dan

If the input text contains bob , my code should print 60 .

Here's what I have so far:

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

How can I fix it?

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

If you want a list of all nums where bob is in the line use a list comprehension:

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

You may also want to split before you check if you want to avoid cases where the name is a substring of a string in the line, for example bob in bobbing -> True:

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

I think a more useful structure would be a dict where the values are all the third numbers in a line associated with each name:

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']})

Through re module.

>>> 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']
#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])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM