【问题标题】:Python Writing A Program To Read and Find The Number Of Matching Letters In 2 Files and Return This NumberPython编写程序读取并查找2个文件中匹配字母的数量并返回这个数字
【发布时间】:2021-08-02 11:48:27
【问题描述】:

这是我到目前为止的代码,我在 2 个文件中使用了 2 组字母,然后我使用 index() 查找匹配的字母数量,然后使用 len() 返回总数 当我运行代码时,我得到了这个, 有19个正确答案

我想知道为什么会这样,正如我所料,有 7 个匹配项,它似乎在计算并返回文本文件中的每个字符

user.txt

A   C   B   A   A   D   B   B   C   A

answers.txt

A   C   A   A   A   B   B   B   C   D
fileObj1 = open("user.txt", 'r')
fileObj2 = open("answers.txt", 'r')

user = fileObj1.read()
answer = fileObj2.read()
results = len([user.index(i) for i in answer])
print("There are", results, "correct answers")

fileObj1.close()
fileObj2.close()

【问题讨论】:

  • 您正在检查第一个文件的每个字符到第二个文件的所有字符,因为您在 answer 变量中循环。您必须同时移动两个文件中的每个字符。
  • @noswear 那么我将如何在我的代码中实现它,你能展示一下吗?我很难理解
  • 欢迎来到 Stack Overflow!运行代码时得到的确切输出是什么,您想要的确切输出是什么?如果您将这些添加到您的问题中,它会更容易提供帮助。
  • 当我阅读它时,这是为了检查多项选择测试的答案,其中一个文件是正确的答案,一个是学生的答案。那是对的吗?上下文有助于了解您的最终目标。

标签: python matching letter file-comparison


【解决方案1】:

嗯,这可能不是优化的方式,但您可以试一试。但是,我还没有测试过。假设两个文件有相同数量的响应。

fileObj1 = open("user.txt", 'r')
fileObj2 = open("answers.txt", 'r')

user = fileObj1.read()
answer = fileObj2.read()
results = 0

for i,j in zip(user,answer):
    if i==j:
        results = results + 1

print("There are", results, "correct answers")

fileObj1.close()
fileObj2.close()

【讨论】:

    猜你喜欢
    • 2023-01-01
    • 2021-01-25
    • 1970-01-01
    • 1970-01-01
    • 2017-06-25
    • 2023-01-12
    • 1970-01-01
    • 2022-09-26
    • 2022-12-04
    相关资源
    最近更新 更多