【问题标题】:Comparing the lines in multiple txt files比较多个txt文件中的行
【发布时间】:2020-07-31 22:05:33
【问题描述】:

我正在编写一个 Python 程序来从文件夹中查找和复制 txt 文件中的行。

我的文件夹结构是

f1--> review.txt
f2--> review.txt
f3--> review.txt

以此类推(f1代表文件夹名)

我想在另一个 txt 文件中找到又出现了哪一行 例如,如果文件“f1/review.txt”的第一行是I want to eat an apple,那么所有其他文件I want to eat an apple 再次出现在其中。我想要一种更有效的方法来做到这一点。我正在编写很多循环来做到这一点并且它变得越来越大

到目前为止我的方法(针对两个文件)

for root,dirs,files in os.walk('root'):
        for file in files:

            with open(os.path.join(root,file), "r") as auto:
                if file == "review.txt":
                    lines=auto.readlines()
                    for line in lines:
                            f=open("root/f1/review.txt","r")
                            src_lines=f.readlines()

                            for src_line in src_lines:


           src_sent=find_error(src_line,src_line_num+':    ')
                                   curr_sent=find_error(line,curr_file_num+':    ')


if src_sent==curr_sent:
       res.append([line_num])

编辑 (可以请格式化以上代码)

txt 文件内容,如果有任何帮助):

classes/CadenceMyProfileController1.cls:6:    Avoid really long classes (lines of code)
/data/public/pmd/repo/src/1/src/classes/CadenceMyProfileController1.cls:6:    Missing ApexDoc comment
/data/public/pmd/repo/src/1/src/classes/CadenceMyProfileController1.cls:6:    The class 'CadenceMyProfileController1' has a Standard Cyclomatic Complexity of 2 (Highest = 174).
/data/public/pmd/repo/src/1/src/classes/CadenceMyProfileController1.cls:6:    The class 'CadenceMyProfileController1' has a total cyclomatic complexity of 422 (highest 215).
/data/public/pmd/repo/src/1/src/classes/CadenceMyProfileController1.cls:6:    This class has too many public methods and attributes
/data/public/pmd/repo/src/1/src/classes/CadenceMyProfileController1.cls:7:    Avoid really long classes (lines of code)

【问题讨论】:

  • 你能告诉我们你尝试了什么吗?
  • 您可能想以熊猫系列的形式阅读您的文件,然后使用:pandas.pydata.org/pandas-docs/stable/reference/api/…
  • 您要检查整行还是单词?
  • @MisterNox 整行(但我确实想丢弃该行的某些部分)
  • @zabop 它是一整行而不是一个单词,因此将其放入 pandas 不会很有效。

标签: python python-3.x linux file


【解决方案1】:

不知道它是否真的比你的短,但你必须触摸每一行,因为你想检查它们是否不同,所以我们必须遍历所有行。在我的解决方案中,它会检查文件的每一行以及其他所有行并将该行更改为"Changed"

但是要小心不可见的"\n",因为这个解决方案说当一行是文件中的最后一行而另一行在中间某处时它们是不同的。如果您需要将其声明为平等,我可以更改它。希望它以某种方式有所帮助:

def check_and_edit(file_path, path_list):
    with open(file_path, "r") as f:
        lines = f.readlines()
    for path in path_list:
        with open(path, "r+") as f:
            target_lines = f.readlines()
            changes = False
            for i, target in enumerate(target_lines):
                if target in lines:
                    target_lines[i] = "Changed \n"
                    changes = True
            if changes:
                f.truncate(0)
                f.seek(0, 0)
                f.writelines(target_lines)

check_and_edit(file_path, path_list)

【讨论】: