将所有从文本文件获得的打印字符串合并到一个列表中

时间:2018-08-24 05:35:38

标签: python python-3.x list

我正在尝试将所有从文本文件中获取的打印字符串合并到一个列表中

我的文本文件:https://drive.google.com/open?id=18tYvYs43vA7ib3br1h1VD75OUU5ho1u8

我的完整代码:

docker inspect <container_name> 

原始

allinstall = open("save_all_install.txt", "r",encoding="UTF-8")

search_words = ["'DisplayName'"]

for line in allinstall:
    if any(word in line for word in search_words):
        # Get the front Display Name Part
        k=line.split('\n')[0]
        #Get the Position I want for excat display name
        print(k[17:-5])
        list = k[17:-5].split(',') 
        # How do I modified here?
        list.extend(list)
        print(list)

预期结果

Windows Driver Package - Intel Corporation (iaStorA) HDC  (04/10/2017 14.8.16.1063)
Windows Driver Package - ASUS (ATP) Mouse  (06/17/2015 6.0.0.66)
Windows Driver Package - Intel (MEIx64) System  (10/03/2017 11.7.0.1045)
Windows Driver Package - ASUS (HIDSwitch) System  (08/18/2015 1.0.0.5)

1 个答案:

答案 0 :(得分:1)

请勿将诸如list之类的python关键字用作变量名。

allinstall = open("save_all_install.txt", "r",encoding="UTF-8")


search_words = ["'DisplayName'"]
result = []

for line in allinstall:
    if any(word in line for word in search_words):
        # Get the front Display Name Part
        k=line.split('\n')[0]
        #Get the Position I want for excat display name
        print(k[17:-5])
        entry = k[17:-5].split(',') 
        # How do I modified here?
        result.append(entry[0])

print(result)

更新: 这也是解决您问题的一种更快,更容易维护的解决方案:

import re

expr = re.compile(r"'DisplayName', '(.+)'")

with open("save_all_install.txt", "r",encoding="UTF-8") as f:
    allinstall = f.readlines()

result = [re.search(expr, line).group(1) for line in allinstall if re.search(expr, line)]
print(result)