python - 比较多个txt文件中的行
问题描述
我正在编写一个 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)
解决方案
不知道它是否真的比你的短,但你必须触摸每一行,因为你想检查它们是否不同,所以我们必须遍历所有行。在我的解决方案中,它检查文件的每一行与其他所有行并将行更改为"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)
推荐阅读
- react-native - 结合 react-navigation 和 redux 时缺少组件道具
- ajax - 无需重新计算公共部分的多个订阅
- laravel - 从 belongsToMany 关系中排除用户
- java - JavaFX TextField 在焦点上将填充更改为 0
- php - 如何转换为laravel?
- python - Python中二维列表的问题
- c# - 将标题中的希伯来文文件名作为内容配置发送到 AngularJS 客户端
- r - 使用函数向 ggplot 添加多个图层
- c# - 如何使用 Sprache 解析条件三元语法 (a > b ? a : b)
- android - 我在 google play store 上有一个 32 位应用程序。2019 年 8 月 1 日之后会发生什么