Skip to main content
 首页 » 编程设计

python之使用python对字符串中的单词进行加权计数

2025年05月04日20bonelee

我有一串单词:

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 

但这似乎行不通,有人知道吗?

请您参考如下方法:

使用字典进行计数;

foo = "This is a string" 
words = foo.split() 
count = {} 
scores = {"this": 3, 
          "is": 5 
} 
 
for word in words: 
    if word not in count: 
        count[word] = 0 
 
    if word in scores: 
        count[word] += scores[word] 
    else: 
        count[word] += 1