Python:有更简单的方法吗?字符串到某些文本

时间:2017-07-13 10:21:22

标签: python string key getvalue

我有这个清单:

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 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

尝试使用item.strip()代替Range("W2").Select ActiveCell.FormulaR1C1 = "=IF(AND(RC[-17]=("Small"),COUNTIF(C[-18],RC[-18])=1),"WARNING","CLEAR")" Range("W2").Select Dim lastrow As Long lastrow = Range("A" & Rows.Count).End(xlUp).Row Range("W2").AutoFill Destination:=Range("W2:W" & lastrow), Type:=xlFillDefault

答案 2 :(得分: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]

答案 3 :(得分:-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