python第五课作业


将全部内容倒序后写入新文件。

打开文件并读取内容

result = []
with open("f:/test/reverse.txt","r") as f:
line = f.readline()
while line:

line = line.strip()

result.append(line[::-1])
line = f.readline()
result = result[::-1]

写入新文件

with open("f:/test/reverse_new.txt","w") as f:
for content in result:
f.write(content)

线程池的方法实现词频统计,以三个文件为例

import re
import threadpool,os

分词

def WordCount(file):
global word_dict
result = []
with open(file,"r") as f:
line = f.readline()
while line:
line = line.strip()
words = re.split("[ ,?.]",line)
for word in words:
if len(word) != 0:
result.append(word)

line = f.readline()

#统计
my_word = dict.fromkeys(result)
for word in result:
my_word[word] = result.count(word)
for k, v in my_word.items():
if k in word_dict.keys():
word_dict[k] += my_word[k]
else:
word_dict[k] = my_word[k]
return word_dict

word_dict = {}
file_list = ["f:/test/word1.txt","f:/test/word2.txt","f:/test/word3.txt"]

线程池

pool = threadpool.ThreadPool(os.cpu_count())
tasks = threadpool.makeRequests(WordCount,args_list=file_list)#file_list代表函数参数列表
[pool.putRequest(task) for task in tasks]
pool.wait()

打印个数

for k,v in word_dict.items():
print(k,":",v)

0 个评论

要回复文章请先登录注册