【问题标题】:search & replace within搜索和替换
【发布时间】:2020-07-20 04:34:45
【问题描述】:

我想逐行解析文件并将固定标点替换为另一个标点(例如,句点“/”与斜杠“.”)仅当该行中的该字符串包含某个变量时

示例:仅当字符串包含 Fx 时才替换

line1: test1/test2
line2: .test + e/y + Fx/var1/var2

输出:

line1: test1/test2
line2: .test + e/y + Fx.var1.var2
 

我该怎么做呢?到目前为止的代码,但我知道它不起作用

import os

textToFind = '/'
textToReplace = '.'
sourcepath = os.listdir('InputFiles/')

def lines_that_contain(string, fp):
    return [line for line in fp if string in line]

for file in sourcepath:
    inputFile = 'InputFiles/'+ file
    print('Conversion is ongoing for:' +inputFile)
    with open(inputFile, 'r') as inputFile:
        for line in lines_that_contain("Fx.", inputFile):
            print('found Fx.')
            fileData = fileData.replace(textToFind, textToReplace)
            freq2 = 0
            freq2 = fileData.count(textToFind)
            
            destinationPath = 'OutputFile/' + file
            with open(destinationPath, 'w') as file:
                file.write(fileData)
                print ('Total %d Record Replaced' %freq2)
        else:
            print('Did not find selected strings')

【问题讨论】:

  • Stackoverflow 上有各种示例解释了实现此目的的方法。例如stackoverflow.com/questions/17140886/…
  • 但我知道这行不通 你能说得更具体些吗?顺便说一句,变量和函数名称应遵循 lower_case_with_underscores 样式。

标签: python file parsing search replace


【解决方案1】:

您的代码存在多个问题:

  • fileData 在设置之前使用。
  • 您的循环仅在包含“触发器”字符串的行上运行,因此您将无法输出未修改的其他行。
  • 如果fileData 应该包含到目前为止读取的所有数据,则替换将影响每一行,无论它是否包含触发器。
  • 输出可能是“Total 0 Record Replaced”,然后是“Did not find selected strings”:您正在计算要替换的文本在替换后的出现次数。由于您的循环不包含 break 语句,因此将评估 else 子句。
  • 您正在为读取的每一行重新创建和写入输出文件。

要解决这些问题,请将列表中的所有行收集起来,如果它们包含触发器,则对其进行修改。读取整个文件后,打开输出文件并转储您收集的行。

import os

textToFind = '/'
textToReplace = '.'
trigger = "Fx."

sourcepath = os.listdir('InputFiles/')

for file in sourcepath:
    inputFile = 'InputFiles/'+ file
    print('Conversion is ongoing for:' + inputFile)
    with open(inputFile, 'r') as infile:
        fileData = []
        replacements = 0
        for line in infile:
            if trigger in line:
                fileData.append(line.replace(textToFind, textToReplace))
                replacements += 1
            else:
                fileData.append(line)

    destinationPath = 'OutputFile/' + file
    with open(destinationPath, 'w') as outfile:
        # The lines already contain terminating \n characters.
        outfile.write(''.join(fileData))

    if replacements > 0:
        print('Total %d Record Replaced' % replacements)
    else:
        print('Did not find selected strings')

由于每一行都是独立处理的,您还可以实现一个流式版本,首先打开输入和输出文件,然后一次读取、处理和写入一行。这就是sed 程序所做的——在shell 中调用sed '/Fx\./ s#/#.#g' inputFile > outputFile 对单个文件执行相同的任务。

【讨论】:

    猜你喜欢
    • 2014-09-13
    • 2019-05-05
    • 2011-02-20
    • 2012-12-25
    • 2010-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多