【问题标题】:Removing duplicate entries in a dictionary删除字典中的重复条目
【发布时间】: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


【解决方案1】:

您只需检查您找到的行是否尚未添加到条目中。为此,您需要检查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]

【讨论】:

  • @AlexHarrisonTas 不客气!如果我的回答解决了您的问题,请将其标记为正确,以便您的问题得到解决,未来的用户将从中受益。
猜你喜欢
  • 2016-03-13
  • 1970-01-01
  • 2013-12-23
  • 1970-01-01
  • 1970-01-01
  • 2019-09-26
  • 1970-01-01
  • 2014-08-01
  • 2013-03-09
相关资源
最近更新 更多