我必须检查文件中是否有某个单词,例如" exe"然后在那句话中找出是否有一个单词,说" mba"然后我必须删除" exe"在千字之后我应该添加"执行"。 rs和千不会出现在下一个旁边。我现在已将文件拆分为行并进行检查。但我不知道如何省略" exe"从文件和如何把"执行"在" mba"之后。你可以帮助我如何使用seekg和seekp,或者你可以给出任何其他解决方案。
f = open(fi+'.o2','r')
ff = open(fi+'.o3','w')
lin = 1
word_count = 1
word = "exe"
word1 = "mba"
for line in f:
if word in line:
print "found in" ,lin
if word1 in line:
print "yes at",word_count
word_count = word_count + 1
lin = lin + 1
示例输入文件:
输出文件应该是:
答案 0 :(得分:3)
这样的事情怎么样?
import re
f = open(fi+'.o2','r')
# f = ['this exe is a mba person',
# 'this exe combo offer is for mba only.',
# 'the exe suite is for mba person.']
word = 'exe'
word1 = 'mba'
for line in f:
# check if both words are in the line
if word in line and word1 in line:
# remove the 'exe' and a space
subs = re.sub(r'\bexe ', '', line)
# replace 'mba' with 'mba executive'
print(re.sub(r'\bmba\b', r'mba executive', subs))
# this is a mba executive person
# this combo offer is for mba executive only.
# the suite is for mba executive person.