0

我正在尝试解析变量“output”中的字符串“External-dep”并创建一个包含其值的字典列表,该变量存在于变量“output”中的多个位置..需要获取最新的。 .values to "External-dep" 总是整数.. 目前卡在下面我无法解析字符串 "External-dep",有人可以提供输入吗?

Master_change ="12345"
external_dep ={}
output="""change Ied13af85dec9128b6a715739b50ae2f33a92cf14
  project: platform/data
  branch: master
  id: Ied13af85dec9128b6a715739b50ae2f33a92cf14
  number: 12345
  subject: code: test
  owner:
    name: danile david
    email: gdavid@com.domain.com
    username: gdavid
  url: https://review-android.company.com/12345
  createdOn: 2013-02-19 18:10:36 PST
  lastUpdated: 2013-04-24 13:43:23 PDT
  sortKey: 0024a01b0003dc6c
  open: true
  status: NEW
  comments:
    timestamp: 2013-04-22 15:20:17 PDT
    reviewer:
      name: danile david
      email: gdavid@com.domain.com
      username: gdavid
    message: Patch Set 4:

             External-dep: 311957
  comments:
    timestamp: 2013-04-24 13:43:23 PDT
    reviewer:
      name: danile david
      email: gdavid@com.domain.com
      username: gdavid
    message: Patch Set 4:

             External-dep: 312994 311957 312591

type: stats
rowCount: 1
runTimeMilliseconds: 4"""

    for line in output :
        if 'External-dep' in line:#make External-dep case-insensitive
            print line

    '''

预期输出:-

    external_dep = {
        '12345': ['312994','311957','312591']
        }

'''
4

2 回答 2

2

以下将为您提供您正在寻找的输出(假设顺序无关紧要,但如果确实如此,请纠正我)。我使用你上面提到的相同的输出字符串,但为了节省空间,这里没有列出。

>>> import re
>>> external_dep = dict()
>>> deps = ' '.join(re.findall(r'(?<=External-dep:\s)[\d ]+(?=\n)', output)).split()
>>> deps
['311957', '312994', '311957', '312591']
>>> external_dep[Master_change] = list(set(deps))
>>> external_dep
{'12345': ['311957', '312994', '312591']}
于 2013-04-28T20:37:24.927 回答
0

如果您赶时间,请使用它,否则请使用更好的东西:

for line in output.splitlines() :
    if 'external-dep' in line.lower():
        print line
        external_dep[Master_change] = list(line.replace("External-dep: ", "").strip().split(' '))

print external_dep

输出:

{'12345': ['312994', '311957', '312591']}
于 2013-04-28T20:38:34.133 回答