栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python基础

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python基础

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')

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/444298.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号