实验二
实验题目
1、请编写一个函数SDSearch(txt, word),其中,txt是一段文本,word是给定的词汇,函数SDSearch可以找到word在txt中的所有位置,并将它们做为返回值返回,编写函数main()调用SDSearch(txt, word),输出SDSearch(txt, word)返回结果。(提示:find(字符串,查找的起始位置))
【代码】
def SDSearch(txt, word):
positions = []
start = 0
while True:
index = txt.find(word, start)
if index == -1:
break
positions.append(index)
start = index + len(word)
return positions
def main():
txt = input(“请输入文本:”)
word = input(“请输入词汇:”)
result = SDSearch(txt, word)
if result:
print(f"‘{word}’ 在文本中的位置:{result}“)
else:
print(f"文本中没有找到 ‘{word}’”)
main()
【实例】
2、编写函数SDrepCount(txt, word, repword),其中,txt是一段文本,word是给定的将要被替换词汇,repword是给定替换的词汇,SDrepCount(txt, word, repword