Python 打印包含字符串的文本文件中的行
我试图获取包含某个字符串的文本文件的行,并在该行中打印第三个数字或字符串。文本文件如下所示:Python 打印包含字符串的文本文件中的行,python,file-search,Python,File Search,我试图获取包含某个字符串的文本文件的行,并在该行中打印第三个数字或字符串。文本文件如下所示: 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) 我怎样
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所在行的所有NUM,请使用列表:
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']})
从集合导入defaultdict
d=默认DICT(列表)
将open(“in.txt”)作为f:
对于f中的行:
如果line.strip():
spl=line.rstrip().split()
d[spl[-1]]。追加(spl[2])
印刷品(d)
defaultdict(,{'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']
你想要的是名字和数字还是仅仅是数字?@mickelodeon612这个
foo12bar12foobar60 bob
,你期望的输出是什么?你的输入是上面的格式吗?@AvinashRaj,为什么你认为单词没有分开?为什么你要使用readlines,而不仅仅是在文件对象上迭代?
#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])