私はリストのリストをテキストでいっぱいのpythonで持っています。それは各文書からの言葉のようなものです。だから、すべてのドキュメントのために私はリストを持っているし、すべてのドキュメントのリストです。どのように辞書の理解を使用して文書内の各単語の出現を数えることができます
すべてのリストにはユニークな単語しか含まれていません。 私の目的は、完全な文書の各単語の出現を数えることです。
for x in texts_list:
for l in x:
if l in term_appearance:
term_appearance[l] += 1
else:
term_appearance[l] = 1
しかし、私は同じことをするために辞書の理解を使いたいと思います。これが初めてです、私は次のように記述することができた、辞書理解を書き込もうとstackoverflowの中に、以前の既存の投稿を使用しています:参照用
from collections import defaultdict
term_appearance = defaultdict(int)
{{term_appearance[l] : term_appearance[l] + 1 if l else term_appearance[l] : 1 for l in x} for x in texts_list}
前の投稿:
Simple syntax error in Python if else dict comprehension
を{{l : term_appearance[l] + 1 if l else 1 for l in x} for x in texts_list}
上記のコードは、PRに成功した:上記の記事で示唆したように
は、私はまた、次のコードを使用しています私の現在の理解を向上させることで任意の助けをいただければ幸いです
[]
[]
[]
[]
Traceback (most recent call last):
File "term_count_fltr.py", line 28, in <module>
{{l : term_appearance[l] + 1 if l else 1 for l in x} for x in texts_list}
File "term_count_fltr.py", line 28, in <setcomp>
{{l : term_appearance[l] + 1 if l else 1 for l in x} for x in texts_list}
TypeError: unhashable type: 'dict'
:最終的には空のリストをoducingが、は、次のトレースバックを投げました。
は、上記のエラーを見て、私はまた、これはエラーなしで走った
[{l : term_appearance[l] + 1 if l else 1 for l in x} for x in texts_list]
を試してみましたが、出力は空のリストでした。
幸運が...ここで考えられている、デフォルトの辞書は、あなたがもし、他の部分を必要としない場合があります意味するゼロにデフォルト設定されます。 – nehemiah