(1)编GtTt)现算文“testtxt”该文本文件中的内容如下所示: Good now, sit down, and tell me, he that knows. Why this same strict and most observant watch So nightly toils the subject of the land, And why such daily cast of brazen cannon, And foreign mart for implements of war, Why such impress of shipwrights, whose sore task Does not divide the Sunday from the week; 第5部分编程测试题 81 What might be toward, that this sweaty haste Doth make the night joint-labourer with the day: Who is't that can inform me? (2)将读取的文本进行分词后放入列表lw中(注意处理大小写和除标点符)并按厅16个单词的格式输出结果,如图 5-2 所示。 调信的结果为: sod nou sit domm and tell me he that knows why this sime strict and mast lstrvant watch so nightlz toils the subiect of the land and sto maoh aily caat of nzen cannen and foreign micrt for implements of war why ruch iwprest of shipnrigits whecs shr it does not divide the sunday from the weok what might be torand that this iweety doth make the nlght oint-lab urer viih the day wno itt that ca inlers me 图5-2输出结果1 (3)根据列表lw的内容生成字典dic(键为单词,值为单词个数)。 (4)根据字典dic,分别输出单词of、and、such、why的个数,按图 5-3所示的格式输出结果。 列表 海结更为: 买,有4个 and有4个 auch有2个 he有3个 图5-3输出结果2 (5)将写程文件名“zhpy”保存算M盘根目录。 请写出代码并说明代码的意思
时间: 2024-01-12 17:03:07 浏览: 159
代码如下:
```python
# 读取文本文件
with open("test.txt", "r") as f:
text = f.read()
# 分词处理
import string
text = text.translate(str.maketrans('', '', string.punctuation))
words = text.lower().split()
# 按16个单词的格式输出结果
lw = []
for i in range(0, len(words), 16):
lw.append(' '.join(words[i:i+16]))
# 输出分词结果
for s in lw:
print(s)
# 生成字典
dic = {}
for word in words:
dic[word] = dic.get(word, 0) + 1
# 输出单词个数
print("of有{}个".format(dic.get("of", 0)))
print("and有{}个".format(dic.get("and", 0)))
print("such有{}个".format(dic.get("such", 0)))
print("why有{}个".format(dic.get("why", 0)))
# 保存文件
with open("M:/zhpy.py", "w") as f:
f.write("这是我的Python代码")
```
代码的意思是:首先读取文本文件"test.txt",然后对文本进行分词处理,去掉标点符号并转为小写,将分词结果按照16个单词的格式输出。接着根据分词结果生成字典,统计单词个数,并输出of、and、such、why的个数。最后将代码保存到文件"zhpy.py"中。
阅读全文