0

我有一个 txt 文件,我需要从中搜索一个正在工作的特定行,但是在该行中我需要去除前 14 个字符,并且我感兴趣的列表元素部分是在运行时动态生成的。所以,场景是我运行了一个脚本,输出保存在 output.txt 中,现在我正在解析它,这是我尝试过的

load_profile = open('output.txt', "r"
read_it = load_profile.read()
myLines = [ ]
for line in read_it.splitlines():
  if line.find("./testSuites/") > -1
   myLines.append(line)
print myLines

这给出了输出: ['*** Passed :) at ./testSuites/TS1/2013/06/17/15.58.12.744_14'] 我只需要解析./testSuites/TS1/2013/06/17/15.58.12.744_14'部分和 2013 并且字符串的 est 是动态生成的。

你能指导我实现它的最佳方法吗?

提前感谢乌尔米

4

2 回答 2

6

使用切片:

>>> strs = 'Passed :) at ./testSuites/TS1/2013/06/17/15.58.12.744_14'
>>> strs[13:]
'./testSuites/TS1/2013/06/17/15.58.12.744_14'

更新:用于lis[0]访问该列表中的字符串。

>>> lis = ['*** Passed :) at ./testSuites/TS1/2013/06/17/15.58.12.744_14']
>>> strs = lis[0]
>>> strs[17:]       # I think you need 17 here
'./testSuites/TS1/2013/06/17/15.58.12.744_14'
于 2013-06-18T16:49:55.660 回答
1

您在问如何去除前 14 个字符,但是如果您的字符串将来不总是具有这种格式怎么办?尝试将字符串拆分为子字符串(删除空格),然后将子字符串包含"./testSuites/"在其中。

load_profile = open('output.txt', "r")
read_it = load_profile.read()
myLines = [ ]
for line in read_it.splitlines():
    for splt in line.split():
        if "./testSuites/" in splt:
            myLines.append(splt)
print myLines

以下是它的工作原理:

>>> pg = "Hello world, how you doing?\nFoo bar!"
>>> print pg
Hello world, how you doing?
Foo bar!
>>> lines = pg.splitlines()
>>> lines
["Hello world, how you doing?", 'Foo bar!']
>>> for line in lines:
...     for splt in line.split():
...             if "Foo" in splt:
...                     print splt
... 
Foo
>>> 

当然,如果您确实对这些行的格式有严格的要求,您可以只使用字符串切片(strs[13:]如 Ashwini 所说),或者您可以拆分行并执行splt[-1](这意味着获取拆分行列表的最后一个元素) .

于 2013-06-18T17:03:49.427 回答