-2

我有这个清单:

comment = ['Item Location: AUMEL222\nLintu Testi: C:\\SSD\\important\\text.txt\nLintu Connection: 123\nItem Version: ABC.123.ABC\nItem Serial: 1234ABCD\nItem Configuration ID: ABCD1234']

我需要从这里提取某些项目。我已经让它工作了,但必须有更简单的方法来做到这一点。我的代码如下所示:

key = "Item Location"
key_found = False
for line in comment:
    if key_found:
        get_value(line)     #converts the big list to more readable state.
line2 = line
teststat = ""
FW = ""
print(line2)
for item in line2.split("\n"):
        if "Item Location" in item:
               Teststat = (item.strip())
        if "Item Version" in item:
                FW = (item.strip())
print(Teststat)
print(FW)

输出:

Item Location : AUMEL222
Item Version : ABC.123.ABC

所以从一个字符串中获取一些想要的值。主要目标是只打印出价值。不是关键。但这可以通过以下方式完成:

print(Teststat.replace("Item Location: ", ""))
4

4 回答 4

2

正则表达式通常是矫枉过正,但它们在这里是一个很好的匹配(蹩脚的双关语,抱歉):

import re
for line in comments:
    found = re.findall(r"(^Item Location|Item Version): (.+?)$", line, re.MULTILINE)
    if found:
        print(found)
        # if you only want the values:
        print("\n".join(v for k, v in found))
        # if you want it as a dict for future use
        found = dict(found)
        print(found)
        # etc
于 2017-07-13T10:44:41.920 回答
1

尝试使用item.split(':')[1]而不是item.strip().

于 2017-07-13T10:26:57.623 回答
0
comment = ['Item Location: AUMEL222\nLintu Testi: C:\\SSD\\important\\text.txt\nLintu Connection: 123\nItem Version: ABC.123.ABC\nItem Serial: 1234ABCD\nItem Configuration ID: ABCD1234']
key = 'Item Location'

#split with \n
commentSplit = comment[0].split('\n')
commentSplit2 = []

#split with ':'
for i in commentSplit:
    commentSplit2.append(i.split(':'))

#value for key
for i in commentSplit2:
 if i[0] == key:
     print i[1]
于 2017-07-13T10:55:03.390 回答
-1

你可能想要这样的东西;

comment = ['Item Location: AUMEL222\n'
           'Lintu Testi: C:\\SSD\\important\\text.txt\n'
           'Lintu Connection: 123\n'
           'Item Version: ABC.123.ABC\n'
           'Item Serial: 1234ABCD\n'
           'Item Configuration ID: ABCD1234']
comment = comment[0]

for key_value_pair in [key_value_pair.split(':') 
                       for key_value_pair in comment.split('\n')]:
    print(':\t'.join(key_value_pair))

请注意,为了便于阅读,我只是将列表中的部分字符串放到新行中,这并没有对comment.


输出:

Item Location:   AUMEL222
Lintu Testi:     C: \SSD\important\text.txt
Lintu Connection:    123
Item Version:    ABC.123.ABC
Item Serial:     1234ABCD
Item Configuration ID:   ABCD1234
于 2017-07-13T10:36:05.103 回答