题目如下
f=open('in.txt','r')
sline=f.readlines()
who=sline[0].strip('\n').split(",")
content="".join(sline[1:])
content=content.replace("\n","")
cishu=dict()
guan=dict()
f.close()
mm=10
for one in who:
c=content.count(one)
cishu[one]=cishu.get(one,0)+c
t=content
while t.count(one)>0:
wz=t.index(one)
nearstr=t[wz-mm if wz-mm>0 else 0:wz+len(one)+mm]
nearstr=nearstr.replace(one,"")
for someone in who:
cc=nearstr.count(someone)
if cc!=0:
guan[(one, someone)]=guan.get((one,someone),0)+cc
t=t[wz+len(one)+mm:]
lcishu=sorted(list(cishu.items()),key=lambda x:(-x[1],int(x[0])))
lcishu=lcishu[:5]
lguan=sorted(list(guan.items()),key=lambda x:(-x[1],int(x[0][0]),int(x[0][1])))
f=open("out.txt","w")
f.write("%s,%s,%s"%("数字","次数","关联数字")+'\n')
for it in lcishu:
f.write("%s,%s,"%(it[0],str(it[1])))
i=0
for si in lguan:
if it[0]==si[0][0] and i<3:
f.write("%s"%( '>'+si[0][1]+":"+str(si[1])))
i=i+1
if lcishu.index(it)<len(lcishu)-1:
f.write("\n")
f.close()
我不知道改哪里
用 list.index 分别取第一行待查找的数字的下标,然后取前后10个数字
将关联度放入字典,以数字为键,出现一次就+1
最后排序输出
import os
import shutil
res_folder = 'results'
if os.path.exists(res_folder):
shutil.rmtree(res_folder)
os.makedirs(res_folder)