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

标签 python python-2.7 line extract

我使用以下代码:

 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/

相关文章:

c++ - 从 C++ 中的文件读取到行尾?

c - 使用 fork() 和 execlp 计算行数

python - docker 化时 pip 要求不匹配

python - 获取 pdb 中的最后一个异常

c - 从文件中删除包含输入单词的行

Python/Pandas - 用另一个数据框中的值替换一个数据框中的元素

python - 使用 Python 时的 BadStatusLine 错误,请求

python - 朴素贝叶斯概率始终为 1

Python:使用准备好的语句更新mysql中的数据

python - 如何将自定义注释从数据框添加到堆积条形图?