python设置了值更改语句,为什么没起作用?
淡淡烟草味
淡淡烟草味 2017-06-28 09:25:55
0
1
785

我想将文件的数据有的则设为原来的值,没有的值则设为0,可是最后结果都是0,代码哪里不正确?
原始数据图片描述
处理结果 图片描述

#!/usr/bin/python
#coding:utf-8
train_data = {}
input_data = open("train_tfidf.txt", "r").readlines()
output_data = open("single_tfidf.txt", "w")
for line in input_data:
    temp_dict = {}
    for i in range(60304):
        temp_dict[i] = 0
    datas = line.split()
    for ele in datas:
        try:
            word_index = ele.split(":")[0]
            tfidf = ele.split(":")[1]
            if word_index == i:
                temp_dict[i] = tfidf
        except:
            continue
    # print temp_dict
    # print word_index, tfidf
    output_data.write(str(temp_dict))
    output_data.write('\n')

  [1]: /img/bVPJMi
  [2]: /img/bVPJMV
淡淡烟草味
淡淡烟草味

全部回复(1)
洪涛

由于你range()跑完了再去遍历的datas,由于range()是个迭代函数,所以在运行datasfor循环的时候,i的值一直是60303,所以也就不满足if word_index == i这个条件了,所以除了60303那项,其他的都还是初始值。其实建议这样改

if word_index == i:
    temp_dict[i] = tfidf

这边可以直接判断temp_dict[word_index]是否存在为0,如果没有定义,则应该是None,所以这块改为

if temp_dict[word_index] == 0:
    temp_dict[word_index] = tfidf
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!