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

2024-07-04 09:07:59 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

我的完整代码:

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)

预期结果

[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)]

Tags: inpackageforsearchwindowsdriverlineopen
1条回答
网友
1楼 · 发布于 2024-07-04 09:07:59

不要使用python关键字,例如list,作为变量名

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)

相关问题 更多 >

    热门问题