如何在python中编辑一行(覆盖和替换)

时间:2014-07-24 21:21:39

标签: python

我有一个文件,我需要编辑该文件中的特定行

我需要编辑这一行:

"file:///c:/xxxxxxx/nameList.json#/"

成:

< xxxx="xxxx://xxxx.com/xxxx//nameList.md">nameList /xxxxxx/

我该怎么做?

请注意,我需要以某种方式存储&#34; nameList&#34;。 我正在编写一个脚本和&#34; nameList&#34;不同文件的部分不同

其他信息:

  1. 我只需要替换&#34; nameList&#34;前面的任何内容。以及&#34; nameList&#34; ....

  2. 之后的任何事情
  3. 但字符串&#34; nameList&#34;对于不同的文件是任意的。例如,第一个文件将具有nameList1,第二个文件将具有nameList2 .....等我需要为不同的文件保留nameListX

2 个答案:

答案 0 :(得分:0)

regex = re.compile("file:///c:/([^/]+)/nameList.json#/")
replacer = lambda g: '< {0}="{0}://{0}.com/{0}//nameList.md">nameList /{0}/'.format(g.groups()[0])

with open("output.txt","w") as f:
    for line in open("input.txt"):
         f.write(re.sub(regex,replacer,line))

也许......我不知道第二个中的xxxx与第一个中的xxxx有什么关系......

如果您只想要“nameList”部分,那么

regex = re.compile("file:///c:/[^/]+/([.]+)\.json#/")
replacer = lambda g: '<xmlns="http://blahblah.com/sub1//{0}.md">{0} /xxxx/'.format(g.groups()[0])

with open("output.txt","w") as f:
    for line in open("input.txt"):
         f.write(re.sub(regex,replacer,line))

答案 1 :(得分:0)

假设xxxx在任何一种情况下都不重要,并且除了扩展名之外,每个输入都是文件名而没有任何其他.,这将得到您想要的输出< / p>

test = "file:///c:/xxxxxxx/nameList.json#/"
parsed_file = test.split('.')[0].split('/')[-1]
result = """< xxxx="xxxx://xxxx.com/xxxx//{0}.md">{0} /xxxxxx/""".format(parsed_file)
print(result)

解决你的意见:

test = "file:///c:/xxxxxxx/nameList.json#/"

def replace_text(s):
    parsed_file = test.split('.')[0].split('/')[-1]
    return("""< xxxx="xxxx://xxxx.com/xxxx//{0}.md">{0} /xxxxxx/""".format(parsed_file))


print(replace_text(test))

with open('results.txt', 'w') as f:
    for line in open("test.txt"):
        if line.startswith('file'):
            f.write(replace_text(line) + '\n')

在此文件上测试:

file:///c:/xxxxxxx/nameList.json#/
random crap
more stuff
file:///c:/xxxxxxx/nameList.json#/
file:///c:/xxxxxxx/nameList.json#/
another one
file:///c:/xxxxxxx/nameList.json#/
file:///c:/xxxxxxx/nameList.json#/
file:///c:/xxxxxxx/nameList.json#/
more crap
file:///c:/xxxxxxx/nameList.json#/
file:///c:/xxxxxxx/nameList.json#/
file:///c:/xxxxxxx/nameList.json#/

oooo this is really getting random
file:///c:/xxxxxxx/nameList.json#/
file:///c:/xxxxxxx/nameList.json#/

这个结果:

< xxxx="xxxx://xxxx.com/xxxx//nameList.md">nameList /xxxxxx/
< xxxx="xxxx://xxxx.com/xxxx//nameList.md">nameList /xxxxxx/
< xxxx="xxxx://xxxx.com/xxxx//nameList.md">nameList /xxxxxx/
< xxxx="xxxx://xxxx.com/xxxx//nameList.md">nameList /xxxxxx/
< xxxx="xxxx://xxxx.com/xxxx//nameList.md">nameList /xxxxxx/
< xxxx="xxxx://xxxx.com/xxxx//nameList.md">nameList /xxxxxx/
< xxxx="xxxx://xxxx.com/xxxx//nameList.md">nameList /xxxxxx/
< xxxx="xxxx://xxxx.com/xxxx//nameList.md">nameList /xxxxxx/
< xxxx="xxxx://xxxx.com/xxxx//nameList.md">nameList /xxxxxx/
< xxxx="xxxx://xxxx.com/xxxx//nameList.md">nameList /xxxxxx/
< xxxx="xxxx://xxxx.com/xxxx//nameList.md">nameList /xxxxxx/