python-3.x - 如何从 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 脚本中的变量中?
解决方案
您可以尝试将整个文件读入一个变量,然后使用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']
推荐阅读
- batch-file - 如果未在批处理脚本中定义 goto,正确的语法是什么?
- javascript - useState 钩子有过时的数据
- google-cloud-platform - GCP的“Longrunningrecognize”输出数据是什么格式的?
- html - 在 bash 脚本中发送邮件时读取字符串消息中的 HTML
- neo4j - Neo4j 中的组和最小关系属性
- javascript - 打开自动创建的pdf php javascript时出现奇怪的语法
- r - 在传单地图中绘制颜色区域
- javascript - 在 for 循环中加载函数 - 变量函数名 [变量]
- r - 使用过滤器时没有得到预期的结果
- java - Java,如何编写或添加而不是覆盖文本文件?