You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python或Pandas从含单引号的文本文件中提取指定字符串

Solution to Extract Name-Path Pairs from Text File

Here's how you can extract the required name and path pairs using Python (with regex for simplicity) or Pandas:

Python with Regular Expressions

This approach is straightforward and handles the text structure cleanly by splitting the file into groups and using regex to capture the quoted values.

import re

# Read the content of your text file
with open('your_input_file.txt', 'r') as file:
    content = file.read()

# Split the content into individual groups separated by "---"
groups = content.split('---')

# Define regex patterns to capture the path and name
path_pattern = re.compile(r"of '([^']+)'")  # Captures text inside quotes after "of "
name_pattern = re.compile(r"hvljhxv '([^']+)'")  # Captures text inside quotes after "hvljhxv "

# Iterate through each group to extract and print the pairs
for group in groups:
    path_match = path_pattern.search(group)
    name_match = name_pattern.search(group)
    
    # Only print if both path and name are found in the group
    if path_match and name_match:
        print(f"{name_match.group(1)} : {path_match.group(1)}")

Pandas Alternative

If you prefer using Pandas (useful if you need to work with the data further), here's how to do it:

import pandas as pd

# Read all lines from the file
lines = pd.read_csv('your_input_file.txt', sep='\n', header=None, names=['line'])

# Filter lines that contain either the path or name markers
relevant_lines = lines[lines['line'].str.contains(r"of '|hvljhxv '", na=False)].reset_index(drop=True)

# Extract paths and names using regex
paths = relevant_lines.iloc[::2]['line'].str.extract(r"of '([^']+)'")[0]
names = relevant_lines.iloc[1::2]['line'].str.extract(r"hvljhxv '([^']+)'")[0]

# Create a DataFrame and print the pairs
result_df = pd.DataFrame({'Name': names, 'Path': paths})
for _, row in result_df.iterrows():
    print(f"{row['Name']} : {row['Path']}")

Both solutions will produce your desired output:

name1 : abcd/cdf
name2 : cdf/abc
name3 : xyz/pmn

Just replace 'your_input_file.txt' with the actual path to your text file.

内容的提问来源于stack exchange,提问作者DCompany

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 10:16:36