1、请编写一个函数SDSearch(txt, word),其中,txt是一段文本,word是给定的词汇, 函数SDSearch可以找到word在txt中的所有位置,并将它们做为返回值返回,编写函数main()调用SDSearch(txt, word), 输出SDSearch(txt, word)返回结果。(提示: find(字符串,查找的起始位置))
def SDSearch(txt, word):
list1 = [] # 定义一个空列表,存放返回的位置
i = 0 # 定义一个变量,相当于指针扫描文本,方便遍历文本
for item in range(len(txt)): # 遍历文本
if txt.find(word, i) != -1: # 如果在文本中存在该词汇,find函数返回-1说明不存在,!= 就是存在的意思。
if txt.find(word, i) not in list1: # 如果文本中不存在该词汇的位置,就将其位置加入到列表中
print(txt.find(word, i)) # 打印位置
list1.append(txt.find(word, i)) # 将其位置加入到列表中
i += len(word) # 如果该位置存在该词汇,就继续向后遍历
else:
i += 1
return list1 # 返回所有的位置
pass
# 测试样例
# address = SDSearch('hugohugoghuohoghugohugo1', 'hugo')
# print(address)
2、编写函数SDrepCount(txt, word, repword),其中,txt是一段文本,word是给定的将要被替换词汇, repword是给定替换的词汇,SDrepCount(txt, word, repword)可以用repword替换txt中出现的所有word, 并返回替换的次数。编写函数main()调用SDrepCount(txt,word, repword),输出SDrepCount(txt, word, repword)返回结果。
import re
def SDrepCount(txt, word, repword):
li = []
i = 0
for item in range(len(txt)):
if txt.find(word, i) != -1:
if txt.find(word, i) not in li:
li.append(txt.find(word, i))
i += len(word)
else:
i += 1
# 以上内容与第一题基本一致
txt = re.sub(word, repword, txt) # txt 就是替换后的文本,re.sub 是利用正则表达式的一个函数将文本中所选单词替换,非常方便。
print(txt) # 我们可以将其输出
return len(li) # len 是一个可以返回列表长度的函数,用此来返回
pass
# 测试样例
# print(SDrepCount('hugohugoghuohoghugohugo1', 'hugo', 'luhe'))
3、请编写一个函数SDfindChinese(txt),其中,txt是一段文本, 函数SDfindChinese可以从txt中找到所有中文,拼接成句子并将其返回。 编写函数main)调用SDfindChinese(txt),输出SDfindChinese(txt)返回结果。
def SDfindChinese(txt):
listChinese = [] # 定义一个空列表以便存放汉字
for item in txt: # 遍历文本,逐个判断字符是否是汉字
if ord(item) < 0 or ord(item) > 256: # 该if语句就是判断一个字符是否是汉字,是根据ASCII码判断的。
listChinese.append(item) # 如果是汉字,就把该字符加入到列表里面
chinese = ''.join(listChinese) # 把列表转化为字符串输出
print(chinese) # 输出获得的中文句子
return chinese
pass
# 下面是测试样例
# SDfindChinese('hkasd我hf是bk中ajs国bff人jasblsfb')