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

如何在C#中读取文本文件中指定前缀后的随机不可预知字符串

嘿,这个需求太常见啦,我给你分享两个实用的Python实现方案,轻松搞定从txt文件提取指定前缀后的内容👇

方法1:逐行读取+字符串分割(简单直接)

如果你的txt文件格式非常规范(每行就是X = 随机字符串的形式),这种方法最容易理解和实现,完全依赖固定前缀匹配,不管后面的内容是什么都能准确提取。

extracted_data = {}

# 替换成你实际的文件路径
file_path = "your_file.txt"

with open(file_path, 'r', encoding='utf-8') as file:
    for line in file:
        cleaned_line = line.strip()  # 去掉换行符和首尾多余空格
        if not cleaned_line:
            continue  # 跳过空行
        
        # 匹配前缀并提取内容
        if cleaned_line.startswith('A = '):
            extracted_data['A'] = cleaned_line[len('A = '):]
        elif cleaned_line.startswith('B = '):
            extracted_data['B'] = cleaned_line[len('B = '):]
        elif cleaned_line.startswith('C = '):
            extracted_data['C'] = cleaned_line[len('C = '):]

# 打印提取结果
print("提取到的内容:")
print(f"A: {extracted_data.get('A', '未找到对应内容')}")
print(f"B: {extracted_data.get('B', '未找到对应内容')}")
print(f"C: {extracted_data.get('C', '未找到对应内容')}")

方法2:正则表达式(更健壮)

如果你的文件格式偶尔有小变动(比如A=和A = 混着写,或者行首有空格),用正则表达式会更灵活,能兼容多种格式变体。

import re

extracted_data = {'A': None, 'B': None, 'C': None}
# 正则规则:匹配A/B/C,后面跟任意数量空格+等号+任意数量空格,最后捕获所有后续内容
pattern = re.compile(r'(A|B|C)\s*=\s*(.*)')

file_path = "your_file.txt"
with open(file_path, 'r', encoding='utf-8') as file:
    for line in file:
        match_result = pattern.search(line.strip())
        if match_result:
            key = match_result.group(1)
            # 去掉内容首尾的多余空格(如果不需要可以去掉.strip())
            value = match_result.group(2).strip()
            extracted_data[key] = value

# 输出结果
print("提取到的内容:")
for key in ['A', 'B', 'C']:
    print(f"{key}: {extracted_data[key] if extracted_data[key] else '未找到对应内容'}")

小提示

  • 记得把代码里的your_file.txt替换成你实际的文件路径哦
  • 如果你的txt文件是一行包含多个键值对(比如A=xxx B=yyy C=zzz),可以用re.findall方法一次性匹配所有内容,只需要把循环里的代码改成matches = pattern.findall(line.strip()),再遍历matches处理就行~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 15:32:54