【发布时间】:2015-11-27 17:07:26
【问题描述】:
我对计算非常陌生,我们被要求制作一个索引,一次读取一行文本,记下特定单词以及它们出现在哪些行上。我已经设法做到了这一点,但是,如果一个单词在同一行上出现不止一次,它会打印它所在的行两次,这在我的测试中是不允许的。
line = 1
x = raw_input ( "Type in line 1 of the paragraph: " ).lower()
text = []
d = {}
while x != ".":
x = convert_sentence(x)
text = [x]
text = string.join(text)
text = string.split(text)
for word in text:
if word in d:
d[ word ] += [line]
else:
d[ word ] = [line]
x = raw_input ( "Enter a full stop to stop: " ).lower()
line += 1
print "the index is"
for index in d:
print index, ":", d[ index ]
这是我运行它时产生的输出:
the index is:
blow : [1, 1]
north : [2, 2]
brisk : [1]
youth : [2]
yesteryear : [4]
wind : [1, 3, 4]
你能帮我弄清楚我做错了什么吗?
【问题讨论】:
-
在 d[word]+=line 之后添加 continue
-
只需检查
if not line in d[word],如果是,请添加它。很简单。
标签: python python-2.x