【问题标题】:Python - replace multipe matches in a string with different replacementsPython - 用不同的替换替换字符串中的多个匹配项
【发布时间】:2014-03-12 04:53:21
【问题描述】:

我有两个文本文件,并将 XXX 占位符替换为第二个文件中的实际匹配项 - 按照第二个文件中给出的顺序。

第一个文本是一个包含多行和多个占位符的文件。

欧盟由以下国家组成 XXX, XXX, XXX, XXX, XXX, .... 欧盟内最大的三个国家是XXX、XXX、XXX。

第二个文件是一个列表,每行一个匹配项:

波兰 荷兰 丹麦 西班牙 意大利 德国 法国

我想将其替换如下:

欧盟由以下国家组成:波兰、荷兰、丹麦、西班牙、意大利...... 欧盟内最大的三个国家是德国、法国、XXX。

到目前为止,我已经完成了这个编码:

import re
file1 = open("text.txt")

file2 = open("countries.txt") 
output = open("output.txt", "w")
countrylist = []

i=0
for line in file2:
    countrylist[i:] = verweise
    i=i+1

j=0
for line in file1:
    if "XXX" in line:
        line = re.sub("XXX", countrylist[j], line)
        j=j+1
    output.write(line)
    output.flush()
output.close

我的问题是正则表达式替换不仅对第一次出现/匹配有效,而且对整个第一行有效。所以我的输出现在看起来像这样:

欧盟由以下国家组成:波兰、波兰、波兰、波兰、波兰、...。 欧盟内最大的三个国家是荷兰、荷兰、荷兰。

如何将每一次出现的 XXX 匹配到我的国家/地区列表的一行?

感谢您的帮助!

【问题讨论】:

    标签: python regex string


    【解决方案1】:

    在 re 模块中 .sub(replacement, string[, count=0]) count=1 应该只替换第一次出现。

    【讨论】:

      【解决方案2】:

      您可以为sub 找到的每个匹配项调用一个函数:

      countries = [ 'Poland', 'Netherlands', 'Denmark', 'Spain', 'Italy' ]
      
      def f(match, countriesIter=iter(countries)):
          return countriesIter.next()
      
      line = "The European Union consists of the following states XXX, XXX, XXX, XXX, XXX"
      
      print re.compile('XXX').sub(f, line)
      

      这将打印:

      The European Union consists of the following states Poland, Netherlands, Denmark, Spain, Italy
      

      根据您的知识,最好使用全局计数器来逐步浏览国家/地区名称列表:

      count = 0
      def f(match):
        global count
        result = countries[count]
        count += 1
        return result
      

      这不太优雅,但如果您对 Python 内部和生成器等没有更深入的经验,则更好理解。

      【讨论】:

        猜你喜欢
        • 2013-02-14
        • 2021-10-17
        • 2017-06-03
        • 2016-09-26
        • 2020-06-05
        • 2020-08-31
        • 2021-03-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多