【问题标题】:How read 3 fields from a text file and write it in single line? [duplicate]如何从文本文件中读取 3 个字段并将其写入单行? [复制]
【发布时间】:2018-08-30 15:50:39
【问题描述】:

我正在尝试从 sample.txt 中读取 3 个值,例如“IP”、“端口”、“名称”,并使用下面给定的 Python 代码打印“IP+端口+名称”:

示例.txt:

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

test.py:

import re

def change_port():
    with open('/Users/test/Desktop/sample.txt', 'rt') as in_file:
        contents = in_file.read()
        result   = re.compile(r'%s.*?%s' % ("IP=", "test1.name="), re.S)
        IP=result.search(contents).group(0)
        result1   = re.compile(r'%s.*?%s' % ("port$test=", "userName"), re.S)
        port= result1.search(contents).group(1)
        result2   = re.compile(r'%s.*?%s' % ("test1.name=", "input.port$test"), re.S)
        name= result2.search(contents).group(2)
        print name+IP+port

change_port()

但我遇到以下错误:

Traceback (most recent call last):
  File "test.py", line 14, in <module>
    change_port()
  File "test.py", line 7, in change_port
    IP=result.search(contents).group(0)
AttributeError: 'NoneType' object has no attribute 'group'

谁能提供解决这个问题的线索?

【问题讨论】:

  • Escape $ and . 另外,捕获.*? -> (.*?) 并得到.group(1)

标签: python regex python-2.7


【解决方案1】:

不使用正则表达式。

演示

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

IP, port, name = "", "", ""
for i in s.split("\n"):
    if "IP" in i:
        IP = i.split("=")[-1]
    if "port" in i:
        port = i.split("=")[-1]
    if "userName" in i:
        name = i.split("=")[-1]
print "IP:{}, Port:{}, Name:{}".format(IP, port, name)

输出:

IP:172.2.1.5, Port:2233, Name:test@test1.com

【讨论】:

    猜你喜欢
    • 2017-12-29
    • 1970-01-01
    • 2018-01-16
    • 1970-01-01
    • 2020-02-20
    • 2021-12-12
    • 1970-01-01
    • 2011-11-06
    • 1970-01-01
    相关资源
    最近更新 更多