python
时间: 2023-06-21 18:20:22 浏览: 38
好的,下面是 Python 的代码实现。请将需要查找的文本以及需要查找的单词作为输入传递给 find_word 函数,将需要替换的单词作为参数传递给 replace_word 函数。
```python
text = "This is a sample text. It contains multiple words and sentences. This is a sample text."
word = "sample"
def find_word(text, word):
count = 0
for w in text.split():
if w == word:
count += 1
print(f"The word '{word}' appears {count} times in the text.")
def replace_word(text, old_word, new_word):
new_text = text.replace(old_word, new_word)
print(f"The new text after replacing '{old_word}' with '{new_word}': {new_text}")
find_word(text, word)
replace_word(text, "sample", "example")
```
输出结果为:
```
The word 'sample' appears 2 times in the text.
The new text after replacing 'sample' with 'example': This is a example text. It contains multiple words and sentences. This is a example text.
```
希望这个代码可以帮助到你。