[英]Using CSV columns to Search and Replace in a text file
背景
我有一个像这样的两列 CSV 文件:
寻找 | 代替 |
---|---|
是 | 曾是 |
一种 | 一 |
乙 | 二 |
等等。
第一列是要查找的文本,第二列是要替换的文本。
我有第二个文件,里面有一些这样的文字:
“这是文本文件中的一段。” (请注意区分大小写)
我的要求:
我想使用该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 函数给出如下:
“这是文本文件中的一个段落。”
其次,我不知道如何在正则表达式模式中使替换区分大小写?
如果有人知道比这个脚本更好的解决方案或者可以改进脚本?
有的话谢谢帮忙。。
我只是将纯字符串放入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'
,但是使用更复杂的正则表达式会很快变得丑陋。这是一种更麻烦的方法(更多代码),但更易于阅读并且不依赖于正则表达式。 事实上,鉴于您的 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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.