regex 使用CSV列在文本文件中搜索和替换

vmjh9lq9  于 11个月前  发布在  其他
关注(0)|答案(3)|浏览(140)

背景

我有一个两列的CSV文件,如下所示:
| 找到|取代|
| --|--|
| 是|是|
| 一|一|
| B|两|

第一列是要查找的文本,第二列是要替换的文本。
我有第二个文件与一些文本这样:
“这是文本文件中的一个段落。”(请注意区分大小写)

我的要求:

我想用那个csv文件文本文件中搜索和替换,有三个条件:-
1.全词替换
1.大小写敏感的替换。
1.替换CSV中每个条目的所有示例

脚本尝试次数:

with open(CSV_file.csv', mode='r') as infile:
    reader = csv.reader(infile)
    mydict = {(r'\b' + rows[0] + r'\b'): (r'\b' + rows[1]+r'\b') for rows in reader}<--Requires Attention
    print(mydict)

with open('find.txt') as infile, open(r'resul_out.txt', 'w') as outfile:
    for line in infile:
        for src, target in mydict.items():
            line = re.sub(src, target, line)  <--Requires Attention
            # line = line.replace(src, target)
        outfile.write(line)

字符串

脚本描述我已经将我的CSV加载到Python字典中,并使用正则表达式来查找整个单词。
问题

我使用r '\B'来创建单词边界,以便进行整个单词替换,但输出在字典中给我“\B”而不是“\B”?
使用REPLACE函数可以得到:
“这是文本文件中的一段。”
第二,我不知道如何在regex模式中使替换区分大小写?
如果有人知道比这个脚本更好的解决方案或可以改进脚本?
谢谢你的帮助,如果有的话。

wkftcu5l

wkftcu5l1#

这里有一个更麻烦的方法(更多的代码),但它更容易阅读,不依赖于正则表达式。事实上,考虑到CSV控制文件非常简单的性质,我通常不会使用csv模块:

import csv

with open('temp.csv', newline='') as c:
    reader = csv.DictReader(c, delimiter=' ')
    D = {}
    for row in reader:
        D[row['Find']] = row['Replace']
    with open('input.txt', newline='') as infile:
        with open('output.txt', 'w') as outfile:
            for line in infile:
                tokens = line.split()
                for i, t in enumerate(tokens):
                    if t in D:
                        tokens[i] = D[t]
                outfile.write(' '.join(tokens)+'\n')

字符串

vmpqdwk3

vmpqdwk32#

我只是把纯字符串放入mydict中,

{'is': 'was', 'A': 'one', ...}

字符串
并替换这一行:

# line = re.sub(src, target, line) # old
line = re.sub(r'\b' + src + r'\b', target, line) # new


请注意,在替换模式中不需要\b。关于您的其他问题,

  • 正则表达式在默认情况下是区分大小写的,
  • '\b'更改为'\B'正是r''所做的。您可以省略r并写入'\\b',但对于更复杂的正则表达式,这很快就会变得丑陋。
eni9jsuy

eni9jsuy3#

为了解决这个问题,我创建了一个PowerShell脚本,它可以帮助你一次替换多个文件中的字符串。
要使用它,您必须创建一个CSV文件,其中包含“FindText”(要替换的文本)和“ReplaceText”(要替换的字符串)列,然后将脚本中的变量“$CsvFile”替换为文件的路径。然后,将变量“$ScanDirectory”替换为文件所在的目录(您需要替换字符串的目录)。
这是我的PowerShell脚本:

$CsvFile = "C:\Users\garci\Desarrollo\powershell\fks.csv"
$ScanDirectory = "C:\Users\garci\Desarrollo\salesforce\UNICOERP\force-app\main\default\lwc"

$Files = Get-ChildItem $ScanDirectory -Recurse
$totalLines = (Import-Csv $CsvFile).count
$currentLine = 0

# Write-Output $totalLines

Import-Csv $CsvFile | ForEach-Object {
    $currentLine += 1
    $percentComplete = ($currentLine / $totalLines) * 100
    # Write-Output $percentComplete
    Write-Progress -Activity "Replace in progress" -Status "$percentComplete% Complete:" -PercentComplete $percentComplete

    Foreach($File in $Files) {
        $content = Get-Content -Path $File.FullName -Raw
        if($content.Length -gt 0){
            $content = $content.Trim()
            $patron = [regex]::Escape($_.FindText)
            
            if( $content -match "\b$patron\b"){
                [regex]::Replace($content,"\b$patron\b",$_.ReplaceText) | Set-Content $File.FullName
            }
        }
    }
}

字符串
保存扩展名为“ps1”的脚本,并使用PowerShell运行它。

注意:如果文件被其他应用程序打开,脚本会失败。
另一个注意事项:regex函数是大小写敏感的,只替换整个单词。

相关问题