1

私は一連の単語を持っています:

foo = "This is a string"

次のようにフォーマットされたリストもあります。

bar = ["this","3"], ["is","5"]

foo で bar の単語を検索するスクリプトを作成する必要があります。単語が見つかった場合、カウンターは bar の単語の隣に数字を追加する必要があります。私はここまで来ました:

bar_count=0
for a,b in foo:
   if bar in a:
       bar_count+=b

しかし、これはうまくいかないようです。

4

6 に答える 6

1

これはあなたのケースでうまくいくはずです

foo = "This is a string"
bar = ["this","3"], ["is","5"]

bar_count = 0
for word, value in bar:
   if foo.count(word) > 0:
       bar_count += int(value)
于 2013-07-15T13:31:48.480 に答える
1

これは明示的なループを使用しておらず (内包表記は別として)、非常に理解しやすいと思います。

import collections
weight_list = ["this","3"], ["is","5"]
foo = "This is a string"

def weighted_counter(weight_list, countstring):
    #create dict {word:count of word}. uses lower() because that's
    # the format of the weight_list
    counts = collections.Counter(countstring.lower().split())

    #multiply weight_list entries by the number of appearances in the string
    return {word:int(weight)*counts.get(word,0) for word,weight in weight_list}

print weighted_counter(weight_list, foo)
#{'this': 3, 'is': 5}
#take the sum of the values (not keys) in the dict returned
print sum(weighted_counter(weight_list, "that is the this is it").itervalues())
#13

実際: http://ideone.com/ksdI1b

于 2013-07-15T13:40:57.440 に答える
1

このコードは、見つかった単語をキーとして辞書を作成し、値はその単語が出現した回数になります。

foo = "This is a string is is"
bar = {}

words = foo.split(" ")

for w in words:
    if(w in bar):
        # its there, just increment its value
        bar[w] += 1
    else:
        # its not yet there, make new key with value 1
        bar[w] = 1

for i in bar:
    print i,"->", bar[i]

このコードは次のようになります。

>>> 
This -> 1
a -> 1
is -> 3
string -> 1
于 2013-07-15T13:30:28.447 に答える
1

合計が必要な場合 - に変換barし、dictそれを使用して有効な単語を検索し、デフォルトで unknown に0実行して実行しますsum

foo = "This is a string"
bar = ["this","3"], ["is","5"]
scores = {w: int(n) for w, n in bar}
bar_count = sum(scores.get(word, 0) for word in foo.lower().split())
# 8

単語数が必要であるが、それぞれを で指定された合計から開始する場合bar:

from collections import Counter
start = Counter({w: int(n) for w, n in bar})
total = start + Counter(foo.lower().split())
# Counter({'is': 6, 'this': 4, 'a': 1, 'string': 1})
于 2013-07-15T13:31:03.587 に答える
1

collections.defaultdictを使用する

>>> foo = "This is a string string This bar"
>>> dic = collections.defaultdict(int)
>>> for f in foo.split():
...     dic[f] += 1
>>> dic
defaultdict(<type 'int'>, {'This': 2, 'a': 1, 'is': 1, 'bar': 1, 'string': 2})

編集

現在持っているこのリストから辞書を作成します。辞書はデータのより良い表現です

>>> foo = 'this is a string this bar'
>>> bar = [['this', 3], ['is', 5]]
>>> dic = dict(bar)
>>> dict(bar)
{'this': 3, 'is': 5}

次に、文字列内の単語を探して追加します

>>> for f in foo.split():
...     try:
...         dic[f] += 1
...     except:
...         pass
>>> dic
{'this': 5, 'is': 6}

それは役に立ちますか?

于 2013-07-15T13:26:48.407 に答える