首页 > 解决方案 > 如何从 txt 中提取某些单词到 Python 变量中?

问题描述

我有一个 .txt 文件,其中存储了 cmd 命令的输出。我想提取文件的某些部分以在 Python 脚本中使用它们。文本文件的内容是:

Profiles from interface  Wi-Fi:


Profiles from group directive (just reading)
---------------------------------------------
    <None>

Users Profiles
-------------------
    Profile from all users     : Home_Network
    Profile from all users     : Work_Network
    Profile from all users     : Stars_Wifi

有什么方法可以在 Python3 中使用read()write()函数,我只能将文件中的网络名称(Home_Network、Work_Network 和 Stars_Wifi)提取到我的 Python 脚本中的变量中?

标签: python-3.xcmd

解决方案


您可以尝试将整个文件读入一个变量,然后使用re.findall

text = ""
with open('path/to/file.txt', 'r') as inp_file:
    text = inp_file.read()

matches = re.findall(r'Profile from all users\s*:\s*(\S+)', text)
print(matches)

['Home_Network', 'Work_Network', 'Stars_Wifi']

推荐阅读