【问题标题】:Semantic Similarity between Sentences in a Text文本中句子之间的语义相似性
【发布时间】:2017-01-11 15:57:19
【问题描述】:

我使用来自here 和以前的论坛页面的材料为一个程序编写了一些代码,该程序将自动计算整个文本中连续句子之间的语义相似度。在这里;

第一部分的代码是从第一个链接复制粘贴的,然后我在下面的 245 行后面放了这些东西。我删除了第 245 行之后的所有多余部分。

with open ("File_Name", "r") as sentence_file:
    while x and y:
        x = sentence_file.readline()
        y = sentence_file.readline()
        similarity(x, y, true)           
#boolean set to false or true 
        x = y
        y = sentence_file.readline() 

我的文本文件是这样格式化的;

红色酒精饮料。新鲜的橙汁。一本英文词典。这 黄色壁纸。

最后我想显示所有旁边有相似度的连续句子对,像这样;

["Red alcoholic drink.", "Fresh orange juice.", 0.611],

["Fresh orange juice.", "An English dictionary.", 0.0]

["An English dictionary.", "The Yellow Wallpaper.",  0.5]

if norm(vec_1) > 0 and if norm(vec_2) > 0:
    return np.dot(vec_1, vec_2.T) / (np.linalg.norm(vec_1)* np.linalg.norm(vec_2))
 elif norm(vec_1) < 0 and if norm(vec_2) < 0:
    ???Move On???

【问题讨论】:

  • 我怀疑这是由某处除以零引起的...此外,SciPy 内置了余弦相似度:docs.scipy.org/doc/scipy/reference/generated/…
  • 在计算余弦相似度之前检查以确保vec_1vec_2 都不是零向量(即长度为零)。只需使用if/else...即,如果向量的范数都是正数,那么您就可以开始了,否则...好吧,跳过那对或抛出异常或...做什么你想做。
  • 那么,如果在计算余弦相似度时遇到范数为零的向量,你想怎么办?抛出错误并退出?默默地继续下一对(假设您在某个for 循环中计算这些,可能是也可能不是这种情况)?这不是我能回答的问题。您必须决定代码的逻辑流程。
  • 您也可以只抛出警告,然后处理输出中的nan 值。
  • 顺便说一下,我不知道您使用什么来编写代码,但您可能希望使用能够指出简单语法错误的 IDE(集成开发环境)或文本编辑器.我推荐 PyCharm:jetbrains.com/pycharm(有免费版和非免费版……免费版足以满足您的需求)。

标签: python vector tf-idf sentence-similarity latent-semantic-analysis


【解决方案1】:

这应该可以。在 cmets 中有几件事需要注意。基本上,您可以遍历文件中的行并随时存储结果。一次处理两行的一种方法是设置一个“无限循环”并检查我们读过的最后一行,看看我们是否已经结束(readline() 将在结束时返回None文件)。

# You'll probably need the file extention (.txt or whatever) in open as well
with open ("File_Name.txt", "r") as sentence_file:
    # Initialize a list to hold the results
    results = []

    # Loop until we hit the end of the file
    while True:
        # Read two lines
        x = sentence_file.readline()
        y = sentence_file.readline()

        # Check if we've reached the end of the file, if so, we're done
        if not y:
            # Break out of the infinite loop
            break
        else:
            # The .rstrip('\n') removes the newline character from each line
            x = x.rstrip('\n')
            y = y.rstrip('\n')

            try: 
                # Calculate your similarity value
                similarity_value = similarity(x, y, True)

                # Add the two lines and similarity value to the results list
                results.append([x, y, similarity_value])
            except:
                print("Error when parsing lines:\n{}\n{}\n".format(x, y))

# Loop through the pairs in the results list and print them
for pair in results:
    print(pair)

编辑:关于您从similarity() 得到的问题,如果您只想忽略导致这些错误的行对(不深入查看源代码,我真的不知道发生了什么),您可以在对similarity() 的调用周围添加try, catch

【讨论】:

  • 您好,我添加了代码,但出现了这些错误(写在问题中)
猜你喜欢
  • 2011-01-03
  • 2020-09-19
  • 1970-01-01
  • 2020-07-11
  • 2015-06-13
  • 1970-01-01
  • 2011-09-29
  • 2016-12-14
  • 2016-08-14
相关资源
最近更新 更多