1

各キーに辞書自体の値がある辞書を作成しようとしています。次のコードの問題は、新しい場合に新しい項目が辞書に追加されないことです

dict_features = {}
def regexp_features(fileids):
    for fileid in fileids:
        if re.search(r'мерзавец|подлец', agit_corpus.raw(fileid)):
            dict_features[fileid] = {'oskorblenie':'1'}
        else:
            dict_features[fileid] = {'oskorblenie':'0'}

        if re.search(r'честны*|труд*', agit_corpus.raw(fileid)):
            dict_features[fileid] = {'samoprezentacia':'1'}
        else:
            dict_features[fileid] = {'samoprezentacia':'0'}
    return dict_features

結果はdictです

{'neagitacia/20124211.txt': {'samoprezentacia': '0'}, 'agitacia/discreditacia1.txt': {'samoprezentacia': '0'}

しかし、私は必要です

{'neagitacia/20124211.txt': {'oskorblenie':'1', 'samoprezentacia': '0'}, 'agitacia/discreditacia1.txt': {'oskorblenie':'0', 'samoprezentacia': '0'}
4

1 に答える 1

1

同じ の値を書き換えていますfileid

あなたのコードでは、

if re.search(r'мерзавец|подлец', agit_corpus.raw(fileid)):
    dict_features[fileid] = {'oskorblenie':'1'}
else:
    dict_features[fileid] = {'oskorblenie':'0'}

if re.search(r'честны*|труд*', agit_corpus.raw(fileid)):
    dict_features[fileid] = {'samoprezentacia':'1'}
else:
    dict_features[fileid] = {'samoprezentacia':'0'}

1 つfileidの の場合、最初のものを作成してから、2 番目の構成を使用してそれを置き換えif-elseます。(または のいずれかが常に実行されるif-elseため、両方の構成体が値を置きます)ifelse

あなたが探しているのはdefaultdictdictデフォルト値としての a です。- の線に沿った何か

>>> from collections import defaultdict
>>> a = defaultdict(dict)
>>> a['abc']
{}
>>> a['abc']['def'] = 1
>>> a
defaultdict(<type 'dict'>, {'abc': {'def': 1}})
>>> a['abc']['fgh'] = 2
>>> a
defaultdict(<type 'dict'>, {'abc': {'fgh': 2, 'def': 1}})

したがって、コードは次のように変更される場合があります

dict_features = defaultdict(dict)
def regexp_features(fileids):
    for fileid in fileids:
        if re.search(r'мерзавец|подлец', agit_corpus.raw(fileid)):
            dict_features[fileid]['oskorblenie'] = '1'
        else:
            dict_features[fileid]['oskorblenie'] = '0'

        if re.search(r'честны*|труд*', agit_corpus.raw(fileid)):
            dict_features[fileid]['samoprezentacia'] = '1'
        else:
            dict_features[fileid]['samoprezentacia'] = '0'
    return dict_features
于 2013-08-02T18:15:26.773 に答える