gpt4 book ai didi

python - 使用来自具有相同名称但不同扩展名的不同文件的数据来获取行号

转载 作者:行者123 更新时间:2023-11-30 23:04:20 24 4
gpt4 key购买 nike

我使用以下代码:

 from collections import defaultdict
import sys
import os
for doc in os.listdir('path1'):
doc1 = "path1" + doc
doc2 = "path2" + doc

doc3 = "path3" + doc
with open(doc1,"r") as words:
sent = words.read().split()
print sent
linenos = {}

with open(doc2, "r") as f1:
for i, line in enumerate(f1):
for word in sent:
if word in line:
if word in linenos:
linenos[word].append(i + 1)
else:
linenos[word] = [i + 1]

matched2 = []
for word in sent:
if word in linenos:
matched2.append('%s %r' % (word, linenos[word][0]))
else:
matched2.append('%s <does not exist>' % word)
with open(doc3,"w") as f1:
f1.write( ', '.join(matched2))

所以,我的path1包含file1.title、file2.title等文件......直到file240.title

同样,我有路径2,其中包含file1.txt、file2.txt等文件......直到tile240.txt

例如:

file1.title 将包含如下数据:

military  troop deployment number need  

file1.txt 将包含:

foreign 1242
military 23020
firing 03848
troop 2939
number 0032
dog 1234
cat 12030
need w1212

输出:

路径3/file1.txt

military 2, troop 4, deployment <does not exist>, number 5, need 8

基本上,代码获取 file1.txt 中存在的单词的行号,并且单词是从 file1.title 输入的。它适用于单个文件,例如一次输入单个文件。但我需要对一个装满文档的文件夹执行此操作。

也就是说,它应该从 file1.title 中读取单词并从 file1.txt 中获取单词的行号,类似地,从 file2.title 中读取单词作为字符串并从 file2.txt 中获取这些单词的行号,等等..

问题是,我无法使用此代码读取具有不同扩展名的相同文件。我应该如何修改它以获得适当的输出?

最佳答案

我猜您是在要求替换文件名字符串中的扩展名,如下所示:

doc2 = "path2" + doc[:-6] + ".txt"

这会从 doc 中删除 6 个字符“.title”,并添加扩展名“.txt”。

关于python - 使用来自具有相同名称但不同扩展名的不同文件的数据来获取行号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33763004/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com