【发布时间】: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