Python3: 如何提取文本文件中的最后一个字段

Python3: How to extract last field in a text file

我正在使用 Python3 在文本文件中搜索字符串,但我无法检索匹配项的最后一个字段。知道有什么问题吗?这是我的代码:

shakes = open("CFTUTIL_idparm0.log","r")
for line in shakes:
    if re.match("(.*) Local partner identifier (.*)", line):
       myPart = line.split(" ")[-2]
       print (myPart,end="",flush=True)
       print(type(line))

此代码适用于除此文件之外的其他文件 test file

Not sure why since the separators are space(s) if I dump the line in hex.

即使所有分隔符都是空格,

split(' ')split() 也会产生非常不同的结果。

为了说明,让我们从您的文件中取出一行:

>>> line = '          Local partner identifier    PART     = W096952B                        \n'

现在,让我们按空格拆分它:

>>> line.split(' ')
['', '', '', '', '', '', '', '', '', '', 'Local', 'partner', 'identifier', '', '', '', 'PART', '', '', '', '', '=', 'W096952B', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '\n']

现在,让我们不带任何参数地拆分它 split:

>>> line.split()
['Local', 'partner', 'identifier', 'PART', '=', 'W096952B']

这两者非常不同。因此,当您采用拆分的最后一个元素时,您会得到非常不同的结果:

>>> line.split()[-1]
'W096952B'

>>> line.split(' ')[-1]
'\n'

解决方案是使用 split() 而不是 split(' ')

文档

您可以使用 python 的交互式文档了解 split 的行为。 运行 help(line.split) 在命令提示符下产生:

关于内置函数拆分的帮助(强调已添加):

Help on built-in function split:

split(...)
S.split([sep[, maxsplit]]) -> list of strings

Return a list of the words in S, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done. If sep is not specified or is None, any whitespace string is a separator and empty strings are removed from the result.

注意最后一行:只有在未指定 sep 或 None 时才会删除空字符串。将 sep 指定为 ' ' 后,所有空字符串都将包含在内,如上所示。