在包含字符串的文本文件中打印行
我试图获取包含特定字符串的文本文件的行,并在行中打印第三个数字或字符串。该文本文件看起来像:在包含字符串的文本文件中打印行
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])
如果希望所有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()]
我认为更有用的结构将是一个字典,其中值都在一条线上阿索第三号与每个名称相关:
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']})
@AvinashRaj,你为什么会认为这些词不是分开的? – 2014-11-04 14:41:26
通过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])
你为什么使用readline而不是迭代文件对象? – 2014-11-04 14:45:43
好点!我会纠正这一点 – meto 2014-11-04 14:49:09
做你想要的名称和数量,或只是多少? – 2014-11-04 14:35:22
只是号码 – mickelodeon612 2014-11-04 14:36:24
@ mickelodeon612这个'foo12bar12foobar60 bob'的预期输出是什么? – 2014-11-04 14:43:13