【问题标题】:Compare texts within a table in python在python中比较表格中的文本
【发布时间】:2017-06-28 09:45:05
【问题描述】:

我想比较 python 列表中的文本。 例如

Url         | text
            |
www.xyz.com | " hello bha njik **bhavd bhavd** bjavd manhbd kdkndsik wkjdk"
            | 
www.abc.com | "bhavye jsbsdv sjbs jcsbjd adjbsd jdfhjdb jdshbjf jdsbjf"
            |
www.lokj.com| "bsjgad adhuad jadshjasd kdashda kdajikd kdfsj **bhavd bhavd** "

现在我想将第一个文本与其他行进行比较,以便了解文本中有多少单词是相似的。 并逐渐第二行与以下行等等....

我应该使用什么方法以及我应该使用什么数据结构?

【问题讨论】:

  • 您只想与以下值进行比较吗?就像 a 和 2 但不是 2 和 1 一样,因为你已经有了价值? (所以相似度矩阵的前半部分)

标签: python string nlp compare nltk


【解决方案1】:

对于python3

如 cmets 中所述,我们生成每个可能的词对,创建集合以确保单词的唯一性,并且我们只计算每对的唯一常用词的数量。如果您的文本列表结构有点不同,这可能需要稍作调整

import itertools

my_list = ["a text a", "an other text b", "a last text c and so on"]

def simil(text_a, text_b):
    # returns the number of common unique words betwene two texts 
    return len(set(text_a.split()).intersection(set(text_b.split())))

results = []
# for each unique combination of texts
for pair in itertools.combinations(my_list, r=2):
    results.append(simil(*pair))

print(result)

旁注:根据您想要做的事情,您可能需要查看诸如 TFIDF (A simple tutorial) 等文本/文档相似性算法,或许多其他算法...

【讨论】:

    【解决方案2】:

    您可以使用OrderedDict() 的最佳方式,这有助于维护获取dict keys 的顺序。

    通过迭代该字典,比较值,您将获得输出

    【讨论】:

      【解决方案3】:

      一种可能的方法是将每个字符串转换为一组单词,然后比较集合的交集

      string_1 = "hello bha njik bhavd bhavd bjavd manhbd kdkndsik wkjdk"
      string_2 = "bhavd dskghfski fjfbhskf ewkjhsdkifs fjuekdjsdf ue"
      
      # First split your strings into sets of words
      set_1 = set(string_1.split())
      set_2 = set(string_2.split())
      
      # Compare the sets to find where they both have the same value
      print set_1 & set_2
      print set_1.intersection(set_2)
      
      # Both print out {'bhavd'}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-20
        • 1970-01-01
        • 2022-12-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多