【发布时间】:2015-03-22 22:14:30
【问题描述】:
大家好, 我有两个文件 File1 和 File2,其中包含以下数据。
File1:
TOPIC:topic_0 30063951.0
2 19195200.0
1 7586580.0
3 2622580.0
TOPIC:topic_1 17201790.0
1 15428200.0
2 917930.0
10 670854.0
等等..有 15 个主题,每个主题都有各自的权重。而像2,1,3这样的第一列是file2中对应单词的数字。例如,
File 2 has:
1 i
2 new
3 percent
4 people
5 year
6 two
7 million
8 president
9 last
10 government
等等..大约有 10,470 行单词。所以,简而言之,我应该在 file1 的第一列而不是行号中有相应的单词。我的输出应该是这样的:
TOPIC:topic_0 30063951.0
new 19195200.0
i 7586580.0
percent 2622580.0
TOPIC:topic_1 17201790.0
i 15428200.0
new 917930.0
government 670854.0
我的代码:
import sys
d1 = {}
n = 1
with open("ap_vocab.txt") as in_file2:
for line2 in in_file2:
#print n, line2
d1[n] = line2[:-1]
n = n + 1
with open("ap_top_t15.txt") as in_file:
for line1 in in_file:
columns = line1.split(' ')
firstwords = columns[0]
#print firstwords[:-8]
if firstwords[:-8] == 'TOPIC':
print columns[0], columns[1]
elif firstwords[:-8] != '\n':
num = columns[0]
print d1[n], columns[1]
当我键入 print d1[2], columns[1] 时,此代码正在运行,为所有行提供 file2 中的第二个单词。但是当打印上面的代码时,它给出了一个错误
KeyError: 10472
file2 中有 10472 行单词。请帮助我解决这个问题。提前致谢!
【问题讨论】:
-
错误回溯到哪一行?
-
文件2的最后一行作为所有的单词。代码 print d1[n], columns[1] 的最后一行给出了错误。
标签: file python-2.7 printing words