开发者

Replacing variable text in between two known elements

s = """Comment=This is a comment
Name=Frank J. Lapidus
GenericName=Some name"""
replace_name = "Dr. Jack Shephard"

I have some text in a file and have been trying to figure out how to search and replace a line so Name=Frank J. Lapidus becomes Name=Dr. Jack Shephard 开发者_开发知识库

How could I do this in Python? Edited: (BTW, the second element would be a \n just in case you were wondering).

Thanks.


Use string.replace (documented under http://docs.python.org/library/stdtypes.html#string-methods):

>>> s = """Comment=This is a comment
... Name=Frank J. Lapidus
... GenericName=Some name"""
>>> replace_name = "Dr. Jack Shephard"
>>> s.replace("Frank J. Lapidus", replace_name)
'Comment=This is a comment\nName=Dr. Jack Shephard\nGenericName=Some name'


You could use the regular expression functions from the re module. For example like this:

import re
pattern = re.compile(r"^Name=(.*)$", flags=re.MULTILINE)
re.sub(pattern, "Name=%s" % replace_name, s)

(The re.MULTILINE option makes ^ and $ match the beginning and the end of a line, respectively, in addition to the beginning and the end of the string.)


Edited to add: Based on your comments to Emil's answer, it seems you are manipulating Desktop Entry files. Their syntax seems to be quite close to that used by the ConfigParser module (perhaps some differences in the case-sensitivity of section names, and the expectation that comments should be preserved across a parse/serialize cycle).

An example:

import ConfigParser
parser = ConfigParser.RawConfigParser()
parser.optionxform = str # make option names case sensitive
parser.read("/etc/skel/examples.desktop")
parser.set("Desktop Entry", "Name", replace_name)
parser.write(open("modified.desktop", "w"))


As an alternative to the regular expression solution (Jukka's), if you're looking to do many of these replacements and the entire file is structured in this way, convert the entire file into a dictionary and then write it back out again after some replacements:

d = dict(x.split("=") for x in s.splitlines() if x.count("=") is 1)
d["Name"] = replace_name
new_string = "\n".join(x+"="+y for x,y in d.iteritems())

Caveats:
First, this only works if there are no '=' signs in your field names (it ignores lines that don't have exactly one = sign).
Second, converting to dict and back will not preserve the order of the fields, although you can at least sort the dictionary with some additional work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜