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

如何用Python从文本文件读取3个字段并拼接为单行输出?

Solution to Extract and Concatenate IP, Port, and Name from sample.txt

Hey there! Let's get this sorted out. The main issue with your current code is that the regex pattern isn't targeting the right keys, and you're not correctly extracting each individual value we need. Let's break this down step by step.

First, let's recap the content of your sample.txt file:

device.IP=172.2.1.5 test1.name=m1234-tsample.test.com input.port$test=2233 userName=test@test1.com passwd=test123 nmae=ryan

Notice the specific keys we need to target:

  • device.IP (for the IP address)
  • input.port$test (for the port number)
  • nmae (for the name – looks like a typo in the file, but we'll work with what's provided!)

Corrected Python Code

Here's the fixed code that properly extracts each value and concatenates them as requested:

import re

def extract_and_concat():
    with open('/Users/test/Desktop/sample.txt', 'rt') as in_file:
        contents = in_file.read()
    
    # Extract IP: capture non-space characters after device.IP=
    ip_match = re.search(r'device\.IP=(\S+)', contents)
    ip = ip_match.group(1) if ip_match else "IP not found"
    
    # Extract port: capture non-space characters after input.port$test= (escape special regex chars)
    port_match = re.search(r'input\.port\$test=(\S+)', contents)
    port = port_match.group(1) if port_match else "Port not found"
    
    # Extract name: capture non-space characters after nmae=
    name_match = re.search(r'nmae=(\S+)', contents)
    name = name_match.group(1) if name_match else "Name not found"
    
    # Concatenate into the required format
    result = f"{ip}{port}{name}"
    print(result)

# Execute the function
extract_and_concat()

Key Changes Explained

  • Targeted Regex: Each pattern uses (\S+) to grab all non-space characters right after the key, ensuring we get the exact value. We also escaped special regex characters like . and $ with backslashes (\., \$) since they have special meaning in regex syntax.
  • Error Resilience: Added checks to handle cases where a key might be missing (so the script won't crash if something's off in the input file).
  • Clean Concatenation: Used an f-string to neatly combine the three values into the IP+port+name format you need.

Expected Output

When you run this code, it will output:

172.2.1.52233ryan

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:38:56