使用python 3在文本替换中保留空白

使用python 3在文本替换中保留空白,python,regex,replace,text-files,Python,Regex,Replace,Text Files,我正在尝试用相应的字符串部分自动替换文件中的源代码文本行。 为此,我创建了一个工作流,以获得两个数据结构,其中包含特定行的所有对应文本。然而,由于我的源代码文件是在咖啡脚本中,所以空格很重要!下面的代码无法检测行中的字符串,因为代码部分开头的空格可变。是否有办法使用通配符或保留空白并进行替换: # -*- coding: utf-8 -*- import fileinput # List of strings to be replaced in the source sourceLis

我正在尝试用相应的字符串部分自动替换文件中的源代码文本行。 为此,我创建了一个工作流,以获得两个数据结构,其中包含特定行的所有对应文本。然而,由于我的源代码文件是在咖啡脚本中,所以空格很重要!下面的代码无法检测行中的字符串,因为代码部分开头的空格可变。是否有办法使用通配符或保留空白并进行替换:

# -*- coding: utf-8 -*-    
import fileinput

# List of strings to be replaced in the source
sourceList = ['name: "My House",','name: "His House",']
# List of target translated strings matching index values with the sourceList
targetList = ['name: "私の家",','name: "彼の家",']

# Loops over sourceList and performs in-place replacement with the value at corresponding index in targetList
for i, val in enumerate(sourceList):
    for line in fileinput.input("seed-staging.coffee", inplace=True):
        print(line.replace(sourceList[i], targetList[i]), end = '') # End part is essential to not get default newline from print 
目的是找到这条线,替换它,保留左侧缩进级别的空白

更新:为Coffee脚本添加源和所需的输出示例

exports.locations = [
    {
        "name": "My House",
         ...
    }
应转向:

exports.locations = [
    {
        "name": "私の家",
         ...
    }

关键是保留空白。

在问题中添加您正在使用的咖啡文件或其精简的示例版本。还要为该sample.Done添加所需的输出。如果需要其他信息,请告诉我。您的实际输出是多少?据我所知,这应该是可行的。在实际输出中,根本没有检测到源中的字符串。什么都没有被取代:我想这是因为开头有空白。它起作用了。在键值对中的键周围也有引号。很抱歉没有意识到这一点!