【问题标题】:Iterating through multiple text files and comparing遍历多个文本文件并进行比较
【发布时间】:2017-01-27 18:24:42
【问题描述】:

我正在尝试编写一个函数,将文本文件放入一个列表中,然后遍历文件以找到准确和部分副本,以清除可能通过抄袭他们的工作而作弊的人。我首先使用我的班级名册并将 .txt 添加到他们的姓名中以查找他们的作业以及他们是否已完成作业。我有超过 500 份学生的论文要阅读。到目前为止,我编写的代码实际上是在 .txt 文件中逐字迭代,所以我得到了太多“被骗”的回报。请帮忙。

def Cheaters():
    file = open("roster.txt", "r")
    L = []
    for i in file:
        new = [i[:-1], ".txt"]
        new2 = "".join(new)
        if i not in L:
            L.append(new2)
    for j in L:
        try:
            file2 = open(j, "r")
            for n in file2:
                for m in file2:
                    if n == m:
                        print("Cheated")
        except:
            print("No work submitted")

【问题讨论】:

  • 首先要定义什么是作弊。查找匹配的词或词对是一个糟糕的指标,因为这些在给定主题中可能很常见。您可能希望按句子分解每个文档并比较文档之间共享的句子数量。如果你想变得非常聪明,你可以实现一个编辑距离,比较从一个文档中的每个句子到另一个文档中的每个句子需要多少次替换。
  • 谢谢。我想检查部分或全部抄袭。你能解释一下我如何逐行而不是逐字迭代吗?另外,“编辑距离”到底是什么意思?比如一系列可以编辑的元素?
  • 我正在编写一些代码来帮助您。所有文档文件名都在 roster.txt 的列表中吗?
  • 名册实际上只是名称,这就是为什么我编写代码来添加 .txt 以添加到名称中以便将文件放入列表中......非常感谢。

标签: python list file iteration


【解决方案1】:

试试这个。您可能需要针对您的文件结构修改它,但它应该是关闭的。

import re
from itertools import product

def hash_sentences(document):
    # remove all characters except those below, replace with a space
    # split into a list
    cleaned_text = re.sub(r'[^A-z0-9,;:\.\?! ]', ' ', document)
    sentences = re.split(r'[\?.!\.]', cleaned_text)

    # the less than 5 removes short sentences like "Dr."
    # return a hash of the sentences for comparison
    return [hash(s.strip().lower()) for s in sentences if len(s) > 5]  

def compare_documents(doc1, doc2):
    hash1 = hash_sentences(doc1)
    hash2 = hash_sentences(doc2)
    # return the percentage of sentences of doc1 that are in doc2
    return sum((h in hash2) for h in hash1) / float(len(hash1))

# get list of document file names
with open('roster.txt', 'r') as fp:
    doc_fnames = [d+'.txt' for d in fp.readlines()]

# create dictionay of file names and content
doc_dict = {}
for fname in doc_fnames:
    try:
        with open(fname, 'r') as fp:
            doc_dict[fname] = fp.read()
    except:
        print('No submission: %s' %fname)

# iterate through the pairs of documents
for doc_pair in product(doc_dict.keys(), doc_dict.keys()):
    pct = compare_documents(doc_dict[doc_pair[0]], doc_dict[doc_pair[1]])
    print('Percentage of %s sentences in %s: %0.2f%%' %(doc_pair[0], doc_pair[1], 100*pct))

【讨论】:

    猜你喜欢
    • 2020-03-08
    • 2017-08-06
    • 2015-01-30
    • 2021-04-22
    • 2020-12-28
    • 2023-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多