[英]Printing the line in a text file that contains a string
我试图获取包含某个字符串的文本文件的行,并在该行中打印第三个数字或字符串。 文本文件如下所示:
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)
我该如何解决?
with open('user_details.txt') as f:
for line in f:
if "bob" in line:
print(line.split()[2])
如果要获取bob在行中的所有数字的列表,请使用列表理解:
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()]
我认为更有用的结构是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']})
通过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']
#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])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.