Python:字符串中有多少相似的单词?

时间:2010-08-24 16:41:08

标签: python string

我有一些类似于这些的丑陋字符串:

   string1 = 'Fantini, Rauch, C.Straus, Priuli, Bertali: 'Festival Mass at the Imperial Court of Vienna, 1648' (Yorkshire Bach Choir & Baroque Soloists + Baroque Brass of London/Seymour)'
   string2 = 'Vinci, Leonardo {c.1690-1730}: Arias from Semiramide Riconosciuta, Didone Abbandonata, La Caduta dei Decemviri, Lo Cecato Fauzo, La Festa de Bacco, Catone in Utica. (Maria Angeles Peters sop. w.M.Carraro conducting)'

我想要一个库或算法,它会给出我们共有多少个单词的百分比,同时排除特殊字符,例如','':'以及'''和{ {1}}等等。

我知道Levenshtein algorithm。但是,这比较了类似 CHARACTERS 的数量,而我想比较它们共有多少 WORDS

3 个答案:

答案 0 :(得分:7)

正则表达式可以很容易地给你所有的话:

import re
s1 = "Fantini, Rauch, C.Straus, Priuli, Bertali: 'Festival Mass at the Imperial Court of Vienna, 1648' (Yorkshire Bach Choir & Baroque Soloists + Baroque Brass of London/Seymour)"
s2 = "Vinci, Leonardo {c.1690-1730}: Arias from Semiramide Riconosciuta, Didone Abbandonata, La Caduta dei Decemviri, Lo Cecato Fauzo, La Festa de Bacco, Catone in Utica. (Maria Angeles Peters sop. w.M.Carraro conducting)"
s1w = re.findall('\w+', s1.lower())
s2w = re.findall('\w+', s2.lower())

collections.Counter(Python 2.7+)可以快速计算单词出现的次数。

from collections import Counter
s1cnt = Counter(s1w)
s2cnt = Counter(s2w)

非常粗略的比较可以通过set.intersectiondifflib.SequenceMatcher完成,但听起来你想要实现一个处理单词的Levenshtein算法,你可以在哪里使用这两个列表。

common = set(s1w).intersection(s2w) 
# returns set(['c'])

import difflib
common_ratio = difflib.SequenceMatcher(None, s1w, s2w).ratio()
print '%.1f%% of words common.' % (100*common_ratio)

打印:3.4% of words similar.

答案 1 :(得分:2)

n = 0
words1 = set(sentence1.split())
for word in sentence2.split():
    # strip some chars here, e.g. as in [1]
    if word in words1:
        n += 1

1How to remove symbols from a string with Python?

编辑:请注意,如果两个句子中的任何一个出现在同一个单词中,则认为这两个句子是相同的 - 要比较位置,可以省略设置转换(只需在两者上调用split()),使用类似:< / p>

n = 0
for word_from_1, word_from_2 in zip(sentence1.split(), sentence2.split()):
    # strip some chars here, e.g. as in [1]
    if word_from_1 == word_from_2:
        n += 1

答案 2 :(得分:2)

Lenvenshtein algorithm本身并不局限于比较字符,它可以比较任何任意对象。经典表单使用字符的事实是一个实现细节,它们可以是任何可以比较相等的符号或结构。

在Python中,将字符串转换为单词列表,然后将算法应用于列表。也许其他人可以帮助你清理不需要的角色,大概是使用一些正则表达魔术。