在Python中修改文本

2024-09-29 10:30:43 发布

您现在位置:Python中文网/ 问答频道 /正文

目前,我在下面导入了文本。

AS400 Storage Management -svc
AS400 Storage Management -svc 2
AS400 Hardware Management -sv 2
AS400 HA sync -app
AS400 HA sync -svc
Bank Users to Cognos
FTP to AS400

我需要使用Python修改它,使其看起来像这样:

(name eq 'AS400 Storage Managemnet -svc'
or name eq 'AS400 Storage Management -svc 2'
or name eq 'AS400 Hardware Management -sv 2'
or name eq 'AS400 HA sync -app'
or name eq 'AS400 HA sync -svc'
or name eq 'Bank Users to Cognos'
or name eq 'FTP to AS400'

我的python脚本是:

fwtext = []
with open("C:/Users/me/PycharmProjects/pythonProject/paloalto/TestText.txt") as f:
    line = f.readline()
    while line:
        line = f.readline()
        fwtext.append(line)
        print("(name eq "+line+"")


with open("C:/Users/me/PycharmProjects/pythonProject/paloalto/fwsearch.txt", "w")as f:
        for line in fwtext:
            f.write("name eq '"+line+"'or ")

它显示在下面。我如何让Python操作我的文本以在eof中包含“(“文本的开头和”)”?我尝试了很多不同的方法来实现这一点,我对Python还是新手

name eq 'AS400 Storage Management -svc 2
'or name eq 'AS400 Hardware Management -sv 2
'or name eq 'AS400 HA sync -app
'or name eq 'AS400 HA sync -svc
'or name eq 'Bank Users to Cognos
'or name eq 'FTP to AS400

Tags: ortoname文本linestoragesyncmanagement
2条回答

核心re库可以轻松完成这些更改

您还可以调用函数进行自定义替换

使用^{}

If repl is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string.

如果你想使用一个包,re可能是你最好的选择,正如上面的人所说。如果您想从头开始编写代码,我认为最简单的方法是将整个输入看作一大块\n分隔的文本,然后使用一些基本的字符串操作:

with open("file_out.txt", "w") as f_out:
    with open("file_in.txt", "r") as f_in:
        data = f_in.read().split("\n")           # get list of all lines
        data = [f"name eq '{v}'" for v in data]  # add the name component to all
        data = "\nor ".join(data)                # join them by 'or ' string
        f_out.write(f"({data})")                 # write out the result in parens

相关问题 更多 >