python - Python在文件中匹配后替换单词
问题描述
我们正在寻找文件中每一行的单词列表中的每个匹配项后替换一个单词
我是山姆经理。你好,你好吗?我很好。这是汤姆主任。很高兴见到你经理山姆。
import re
f1=open('testinput.txt', 'r')
f2=open('testoutput.txt', 'w')
checkWords = ["Manager","Director"]
repWords = ("*** ")
for line in f1:
i = 0
for i in range(len(checkWords)):
# Find the next word after the search word
list1 = re.compile(r'%s\s+((?:\w+(?:\s+!$)) {1})' %checkWords[i]).findall(line)
checkWords = ','.join(list1)
print(checkWords)
line = line.replace(checkWords, repWords)
print(line)
f2.write(line)
f1.close()
f2.close()
预期输出:
This is Manager *** speaking.Hello, how are you?
I am Fine. this is Director *** Nice to Meet you Manager ***
但是,我现在得到的输出:
*** T*** h*** i*** s*** *** i*** s*** *** M*** a*** n*** a*** g*** e*** r*** *** S*** a*** m*** *** s*** p*** e*** a*** k*** i*** n*** g*** .*** H*** e*** l*** l*** o*** ,*** *** h*** o*** w*** *** a*** r*** e*** *** y*** o*** u*** ?***
解决方案
lines=open('testinput.txt', 'r').read().split('\n')
checkWords = ["Manager","Director"]
repWords = "***"
out = []
flag = False
for line in lines:
line_out = []
for word in line.split(' '):
if flag:
line_out.append(repWords)
flag = False
else:
line_out.append(word)
if word in checkWords:
flag=True
out.append(' '.join(line_out))
with open('testoutput.txt', 'w') as f2:
f2.write('\n'.join(out))
这是你需要的吗?
推荐阅读
- flutter - 使用 getx 和颤振堆栈溢出错误
- abap - 如何在 ABAP 中进行对象-关系映射?
- angular - Angular Reactive FormControl.valueChanges 未触发
- mediawiki - MediaWiki 的 Minerva 移动皮肤未显示 MediaWiki:Loginprompt
- javascript - NextJS/React 组件不会在开发中编译 - 没有给出错误
- flutter - Flutter 中有没有办法使用 Lint 进行多次更正?
- android - IDE 中的 HiltAndroidApp/HiltViewModel “未解决的参考”,但它仍然可以正常构建
- amazon-web-services - Terraform for 循环生成安全组规则
- angular - 使用(Spring Boot + Angular)混合项目结构时如何保持一致的 Angular 版本?
- ansible - 从 C# 获取 Ansible Tower API 身份验证令牌