1

2つのコンテナーの違いを取得しようとしていますが、コンテナーが奇妙な構造になっているため、違いを実行するための最良の方法がわかりません。1つのコンテナのタイプと構造は変更できませんが、他のコンテナは変更できます(可変デリム)。

delims = ['on','with','to','and','in','the','from','or']
words = collections.Counter(s.split()).most_common()
# words results in [("the",2), ("a",9), ("diplomacy", 1)]

#I want to perform a 'difference' operation on words to remove all the delims words
descriptive_words = set(words) - set(delims)

# because of the unqiue structure of words(list of tuples) its hard to perform a difference
# on it. What would be the best way to perform a difference? Maybe...

delims = [('on',0),('with',0),('to',0),('and',0),('in',0),('the',0),('from',0),('or',0)]
words = collections.Counter(s.split()).most_common()
descriptive_words = set(words) - set(delims)

# Or maybe
words = collections.Counter(s.split()).most_common()
n_words = []
for w in words:
   n_words.append(w[0])
delims = ['on','with','to','and','in','the','from','or']
descriptive_words = set(n_words) - set(delims)
4

5 に答える 5

3

wordsすべての区切り文字を削除して変更するのはどうですか?

words = collections.Counter(s.split())
for delim in delims:
    del words[delim]
于 2012-03-29T09:44:01.653 に答える
1

これは私がそれをどのように行うかです:

delims = set(['on','with','to','and','in','the','from','or'])
# ...
descriptive_words = filter(lamdba x: x[0] not in delims, words)

フィルタ方式を使用します。実行可能な代替案は次のとおりです。

delims = set(['on','with','to','and','in','the','from','or'])
# ...
decsriptive_words = [ (word, count) for word,count in words if word not in delims ]

がO(1)ルックアップdelimsを可能にするセットに含まれていることを確認します。

于 2012-03-29T09:41:18.287 に答える
1

最も簡単な答えは次のとおりです。

import collections

s = "the a a a a the a a a a a diplomacy"
delims = {'on','with','to','and','in','the','from','or'}
// For older versions of python without set literals:
// delims = set(['on','with','to','and','in','the','from','or'])
words = collections.Counter(s.split())

not_delims = {key: value for (key, value) in words.items() if key not in delims}
// For older versions of python without dict comprehensions:
// not_delims = dict(((key, value) for (key, value) in words.items() if key not in delims))

それは私たちに与えます:

{'a': 9, 'diplomacy': 1}

別のオプションは、先制的にそれを行うことです:

import collections

s = "the a a a a the a a a a a diplomacy"
delims = {'on','with','to','and','in','the','from','or'}
counted_words = collections.Counter((word for word in s.split() if word not in delims))

ここでは、単語のリストをカウンターに渡す前にフィルターを適用します。これにより、同じ結果が得られます。

于 2012-03-29T10:02:20.290 に答える
0

パフォーマンスのために、ラムダ関数を使用できます

filter(lambda word: word[0] not in delim, words)
于 2012-03-29T09:51:16.523 に答える
0

とにかくそれを繰り返しているのなら、なぜそれらをセットに変換するのをわざわざするのですか?

dwords = [delim[0] for delim in delims]
words  = [word for word in words if word[0] not in dwords]
于 2012-03-29T09:42:08.403 に答える