2015-11-27 163 views
0

我对计算非常陌生,并且我们被要求创建一个索引,该索引一次读取一行文本,记下特定单词以及它们出现在哪些行上。但是,我设法做到这一点,如果一个单词不止一次出现在同一行上,它会打印两次,这不适用于我的测试。删除字典中的重复条目

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] 

能否请你帮我找出我做错了吗?

+0

附加继续d [文字]后+ =行 –

+0

只是检查'在d [文字]如果不是线',如果是添加它。简单。 –

回答

0

你只需要检查你发现的行是否已经被添加到条目。为此,您需要检查if not line in d[word]。此外,要将元素添加到list,您可以使用.append()方法,该方法比+运算符更易于理解。

下面是正确的代码:

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: 
      if not line in d[word]: 
       d[word].append(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] 
+0

非常感谢你我真的很感激! –

+0

@AlexHarrisonT欢迎您!如果我的答案解决了您的问题,请将其标记为正确,以便您的问题得到解决,未来的用户将从中受益。 –