下面是一个Python程序的示例,它可以从给定的.txt文件中查找、替换和计算单词的次数。
def find_replace_word(file_name, word_to_find, word_to_replace):
try:
with open(file_name, 'r') as file:
content = file.read()
# 查找单词并替换
replaced_content = content.replace(word_to_find, word_to_replace)
# 计算单词出现的次数
word_count = content.count(word_to_find)
# 将替换后的内容写回文件
with open(file_name, 'w') as file:
file.write(replaced_content)
return word_count
except FileNotFoundError:
print("文件不存在")
return -1
# 示例使用
file_name = "example.txt"
word_to_find = "apple"
word_to_replace = "orange"
word_count = find_replace_word(file_name, word_to_find, word_to_replace)
if word_count >= 0:
print("单词 '{}' 被替换了 {} 次".format(word_to_find, word_count))
请注意,这只是一个示例,实际使用时可能需要根据具体需求进行调整。另外,程序会将替换后的内容写回到原文件中,请确保备份文件以防止意外的数据丢失。