第八章习题

本文介绍了如何处理一个包含英文单词的文件,通过两种方法找出只出现一次的单词。同时,探讨了如何在Python中创建不可变集合,并在尝试向其添加或修改元素时捕获异常。此外,还列举了几种常见的排重方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、一个文件由英文单词组成,找出文件中只出现一次的单词
方法1:

#ncoding=utf-8
import string
only_one_word = []
with open("e:\\testman\\a.txt",'r',encoding="utf-8") as fp:
    content = fp.read()

for i in content:
    if i in string.punctuation:
        content.replace(i," ")

for word in set(content.split()):
    only_one_word.append(word)

print(only_one_word)

方法2:

import string
with open("e:\\testman\\a.txt",'r',encoding="utf-8") as fp:
    content = fp.read()

for i in content:
    if i in string.punctuation:
        content.replace(i," ")
word_list = []
for word in content.split():
    if content.split().count(word) == 1:
        word_list.append(word)

print(word_list)

2、定义一个不可变集合,向不可变集合中添加元素或者修改已有元素,并捕获异常

f_set = frozenset('12345678')
print(f_set)
try:
    f_set.add(9)
except AttributeError as e:
    print(e)
except Exception as e:
    print(e)
else:
    print("no error!")

在这里插入图片描述
3、列出你所有知道的排重方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值