python - 如何将文件中的字符串更改为列表中的字符串

标签 python string file list

我是 Python 编程的新手,我遇到了一个棘手的问题,即用存储在列表中的字符串更改文本文件中的特定字符串。

我正在处理媒体 wiki 文档 - 将它们从 .doc 转换为 wiki 代码。转换后,所有图像都被标签 [[Media:]] 替换 - 我想用存储在列表中的图片名称替换所有 [[Media:]] 标签。例如,在转换后的文档中会有 5 个 [[Media:]] 标签,所以这意味着我有这样的列表:

li = ["image1.jpg", "image2.jpg", "image3.jpg", "image4.jpg"]

我想将文档中的第一个标签更改为 bo 替换为 image1.jpg,文档中的第二个标签替换为 image2.jpg 等等。

这是一段代码,但我不知道如何通过列表进行迭代

li = ["image1.jpg ", "image2.jpg ", "image3.jpg ", "image4.jpg ", "image5.jpg "]
a = 0

src = open('sap.txt').readlines()
dest = open('cel.txt', 'w')

for s in src:
    a += 1
    dest.write(s.replace("[[Media:]]", li[a]))
dest.close()

我将不胜感激

最佳答案

一种简单但不是很有效的方法是一次替换一个标签:

>>> li = ["image1.jpg", "image2.jpg", "image3.jpg", "image4.jpg"]
>>> s = "a tag [[Media:]] - I want to replace all [[Media:]] tags with a names of pictures stored in a list. For example in a converted document there will be 5 [[Media:]] tags d by a tag [[Media:]] - I want to replace all [[Media:]] tags"
>>> for item in li:
...    s = s.replace("[[Media:]]", item, 1)  # max. 1 replace per call
...
>>> s
'a tag image1.jpg  - I want to replace all image2.jpg  tags with a names of pictures stored in a list. For example in a converted document there will be 5 image3.jpg  tags d by a tag image4.jpg  - I want to replace all image5.jpg  tags'

更好的方法是一次性构建字符串:

def interleave(original, tag, replacements):
    items = original.split(tag)
    return "".join((text+repl for text,repl in zip(items, replacements+[""])))

像这样使用它:

>>> interleave(s, "[[Media:]]", li)
'a tag image1.jpg  - I want to replace all image2.jpg  tags with a names of pictures stored in a list. For example in a converted document there will be 5 image3.jpg  tags d by a tag image4.jpg  - I want to replace all image5.jpg  tags'

关于python - 如何将文件中的字符串更改为列表中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20146368/

相关文章:

c# - 在 C# 中将一个字符串拆分为另一个字符串

c - 将文件中的数组读入数组然后将其打印到另一个文件时遇到问题

java - 多线程写入文件时的行为

php - 长时间运行的 Golang 程序和资源(文件句柄、tcp 连接等)

Python2正则表达式似乎有问题

python:两个配对列表的索引/分页

python - 在Python中过滤具有许多键值对的列表

python - 只要条件为真,Panda 就会连续累加时间

regex - 如何计算字符串中某个字符的频率?

string - 如何从字符串中删除重复的空格