1

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

第一部分的代码是从第一个链接复制粘贴的,然后我在下面的 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???
4

1 回答 1

0

这应该有效。评论中有几点需要注意。基本上,您可以遍历文件中的行并随时存储结果。一次处理两行的一种方法是设置一个“无限循环”并检查我们读到的最后一行,看看我们是否已经结束(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(),如果您只想忽略导致这些错误的行对(不深入查看源代码,我真的不知道发生了什么),您可以try, catch在打电话给similarity().

于 2017-01-11T16:18:40.500 回答