【问题标题】:How to remove certain words within a dictionary如何删除字典中的某些单词
【发布时间】:2018-10-21 05:53:39
【问题描述】:

我有一个字典,其中包含值作为列表,每个列表都包含字符串。我想 1) 删除标点符号,不包括 @ 和 2) 删除列表中带有“@”的项目。然而,我似乎无法得到第二部分:

>>> dat = {'2008':['what!','@cool','#fog','@dddong'],'2010':['hey','@cute']}
>>> 
>>> def remove_rounds(data):
...     import json
...     import string
...     ndata = {}
...     punct = string.punctuation
...     rpunct = punct.replace('@',"") # withold @
...     for k,v in data.items():
...         alist = []
...         ndata[k] = []
...         for word in data[k]:
...             alist.append(word.strip(rpunct))
...             ndata[k] = alist
...     sdata = {}
...     for k,v in ndata.items():
...         sdata[k] = []
...         blist = []
...         for word in ndata[k]:
...             if word.startswith('@'):
...                 blist = ndata[k].remove(word) # returns the list
...                 sdata[k] = blist
...     return sdata
... 
>>> remove_rounds(dat)
{'2008': None, '2010': None}

所以,ndata 部分工作正常,我能够删除列表中的标点符号,但我似乎无法使用相同的逻辑来删除以“@”开头的单词。我也不明白为什么不能应用相同的逻辑。

【问题讨论】:

    标签: python-3.x dictionary


    【解决方案1】:

    如果它以@开头,请避免附加单词:

    dat = {'2008':['what!','@cool','#fog','@dddong'],'2010':['hey','@cute']}
    
    def remove_rounds(data):
        import string
        ndata = {}
        punct = string.punctuation
        rpunct = punct.replace('@',"") # withold @
        for k,v in data.items():
            alist = []
            ndata[k] = []
            for word in data[k]:
                if word.startswith("@"):
                    continue # ignore this word and continue with the next one
                alist.append(word.strip(rpunct))
                ndata[k] = alist
    
        return ndata
    
    print(remove_rounds(dat))
    

    结果:

    {'2008': ['what', 'fog'], '2010': ['hey']}
    

    【讨论】:

    • 哦,哇,所以您只需忽略带有“@”的单词,然后删除其他单词的点并附加它们。这是有道理的。
    • @song0089 ndata[k].remove(word)修改了列表inplace,也就是说ndata[k]被改变了,但是方法返回了None,所以blistNone的时候你分配sdata[k] = blist
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 2022-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多