一.样例文件–如果你有一个文本内容如下可以借鉴下面python脚本导入至excel
/webcenter
127.0.0.1:8888,127.0.0.1:8809
/bank-bl
127.0.0.1:80
/cscec-backend
127.0.0.1:8080,127.0.0.1:8080
二.执行步骤如下
1.需要本地环境安装安装Python(mac)…(或者自己搜索安装)—如果已安装请忽略
1.brew install python
2.下载会显示(查看)安装地址
3.修改配置文件并做验证
//查看配置文件
cat ~/.bash_profile
//添加配置
export PATH="/opt/homebrew/opt/python@3.13/libexec/bin:$PATH"
//生效
source ~/.bash_profile
//验证
which python 或者python --version
4.验证如下-显示安装成功
5.需要依赖环境确保已经安装了 pandas 和 openpyxl
pip install pandas openpyxl
6.使用虚拟环境(推荐)为了避免依赖冲突或权限问题,强烈建议使用虚拟环境来管理项目的依赖。以下是创建和使用虚拟环境的步骤:
- 创建虚拟环境:
## 创建虚拟环境
python -m venv myenv
##对于 Linux/macOS---激活虚拟环境
source myenv/bin/activate
##或者对于 Windows:
##myenv\Scripts\activate
#在虚拟环境中安装所需的库
pip install pandas openpyxl
#运行python脚本(创建脚本如下-标题7-有异常会有日志显示那些没解析成功会继续解析)
python parse_urls.py
7.Python脚本内容如下
import re
import pandas as pd
def parse_urls(file_path):
with open(file_path, 'r') as file:
lines = file.readlines()
result = []
path = None
for line in lines:
stripped_line = line.strip()
if not stripped_line:
continue # Skip empty lines
if stripped_line.startswith('/'):
path = stripped_line # Keep the leading '/'
elif path:
urls = [url.strip() for url in stripped_line.split(',')]
for url in urls:
match = re.match(r'([^:]+):(\d+)', url)
if match:
domain, port = match.groups()
result.append({'Path': ensure_leading_slash(path), 'Domain': domain, 'Port': port})
else:
print(f"Warning: Could not parse URL {url}")
path = None # Reset path after processing
return result
def ensure_leading_slash(path):
"""Ensure the path starts with a slash."""
return path if path.startswith('/') else '/' + path
def write_to_excel(parsed_data, output_file):
df = pd.DataFrame(parsed_data)
df.to_excel(output_file, index=False)
if __name__ == "__main__":
input_file = '/Users/shf/Desktop/untitled' # Replace with your actual file path
output_file = 'parsed_urls.xlsx' # Output Excel file name
parsed_data = parse_urls(input_file)
write_to_excel(parsed_data, output_file)
print(f"Data has been successfully written to {output_file}")
8.会得到一个名为 parsed_urls.xlsx 的 Excel 文件,其中包含三列:Path、Domain 和 Port,如下所示:
P.S:
- input_file:是你的文件路径
- output_file:生成的Excel文件名称,不指定会生成到当前路径目录下
- parse_urls 函数:该函数接收一个文件路径作为参数,逐行读取文件内容并解析。它会识别以斜杠开头的行作为路径,并将其后的行视为对应的 URL 列表。然后,它会为每个 URL 创建一个字典条目,包含路径、域名和端口,并添加到结果列表中。
- write_to_excel 函数:该函数接收解析后的数据列表和输出文件名作为参数,使用 pandas 将数据转换为 DataFrame,并将其写入指定的 Excel 文件中。
- 正则表达式匹配:re.match(r’(+):', url) 用于分离域名和端口号。它假设 URL 格式为 domain:port
- 主程序逻辑:指定要解析的文件路径和输出的 Excel 文件名,调用 parse_urls 进行解析,然后调用 write_to_excel 将结果保存到 Excel 文件中。
9.下次想再次使用虚拟环境进行操作可以执行一下步骤
a.找到上面 1.创建虚拟环境时会下在文件的路径所在层级(查找自己的)
/opt/homebrew/bin
b.执行激活命令
source myenv/bin/activate
c.如果想退出/停用当前环境执行如下命令
deactivate
d.(可选)也可配置在 .bashrc 或 .zshrc 文件中(mac),因为不常用我就不配置了,仅此记录一下,本人容易忘。
alias activate_myenv='source /path/to/your/project/myenv/bin/activate'