2

大家好,我有多个带有字符串的列表。铁:

params = {
   "str1":"A Teststring which tests.",
   "str2":"Strings are awesome to test",
   "str3":"Teststring is a string that tests ",
   "str4":"String awesome test tests"
   }


erg =[]
allstrings = ['str1','str2','str3','str4']
userkeywords = ['teststring','awesome','test','string']
for str in allstrings:
    strkeywords = params[str].split()
    common = list(set(userkeywords) & set(strkeywords) )
    howmuch = len(common)
    erg.append(howmuch)
print erg

使用此代码,我得到参数字符串中有多少单词是相同的。但是我怎样才能打印出与用户关键字有最多共同词的字符串。

期待:

str1 : 4
str2: 3
str4: 3

(数字是例子)

任何人都可以帮忙吗?

4

1 回答 1

0

对 使用不同的数据结构erg,即 a dict

erg = {}
allstrings = ['str1','str2','str3','str4']
userkeywords = set(['teststring','awesome','test','string'])
for strs in allstrings:
    strkeywords = params[strs].split()
    #len() works on sets too, no need to convert this to a list
    common = len( userkeywords & set(strkeywords) )
    erg[str] = common

for k in sorted(erg, key=erg.get, reverse=True):
    print k, ':', erg[k]

输出:

str2 : 2
str4 : 2
str3 : 1
str1 : 0
于 2013-11-01T14:36:50.537 回答