Python稳基修炼的经典案例13(计算机二级、初学者必会的字符文件处理)

2023-05-16

文章目录

        • 1、统计基础中文字符
        • 2、中文版凯撒加密
        • 3、提取网页链接,即“href=”后面的的链接

1、统计基础中文字符

  • 题:给定基础中文字符的unicode编码范围为{0x4e00, 0x9fa5},统计文本文件中存在多少的基础中文字符及其对应的次数
fi = open("a.txt", 'r', encoding='gbk')
fo = open("c.txt", 'w', encoding='gbk')
txt = fi.read()
d = {}
for c in txt:
    if 0x4e00 <= ord(c) <= 0x9fa5:
        d[c] = d.get(c, 0) + 1
        ls = []
for key in d:
    ls.append("{}(0x{:x}):{}".format(key, ord(key), d[key]))
fo.write(",".join(ls))
fi.close()
fo.close()

01


2、中文版凯撒加密

s = input("请输入明文:")
d = {}
for c in [0x4e00, 0x9fa5]:
    for i in range(20902):
        d[chr(i+c)] = chr((i+10451)%20902+c)
print("凯撒加密后的文字:" + " ".join([d.get(c, c) for c in s]))

02


3、提取网页链接,即“href=”后面的的链接

fi = open("sweb.html", 'r', encoding='utf-8')
fo = open("text-urls.txt", 'w', encoding='utf-8')
txt = fi.read()
ls = txt.split(" ")
urls = []
for item in ls:
    if item[:5] == "href=" and item[6:13] == "http://":
        urls.append(item[6:-1])
        for item in urls:
            fo.write(item+'\n')
fi.close()
fo.close()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python稳基修炼的经典案例13(计算机二级、初学者必会的字符文件处理) 的相关文章

随机推荐