Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/flash/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在另一个文本文件中查找文件名,如果是,如何在相应的行中提取信息?_Python_Python 2.7_For Loop - Fatal编程技术网

Python 如何在另一个文本文件中查找文件名,如果是,如何在相应的行中提取信息?

Python 如何在另一个文本文件中查找文件名,如果是,如何在相应的行中提取信息?,python,python-2.7,for-loop,Python,Python 2.7,For Loop,在下面的代码中,我打开一个文件列表,并检查文件列表中的每个文件 如果文件的名称与另一个文本文件中每行的前4个字符相对应,我用line.split()[1]提取写入文本文件的数字,然后将此字符串的int指定给d。之后,我将使用这个d来划分计数器 以下是我的部分功能: fp=open('yearTerm.txt' , 'r') #open the text file def parsing(): fileList = pathFilesList() for f in fileLi

在下面的代码中,我打开一个
文件列表
,并检查
文件列表中的每个
文件

如果
文件的名称
与另一个文本文件中每行的前4个字符相对应,我用
line.split()[1]
提取写入文本文件的数字,然后将此字符串的int指定给
d
。之后,我将使用这个
d
来划分计数器

以下是我的部分功能:

fp=open('yearTerm.txt' , 'r') #open the text file
def parsing():
     fileList = pathFilesList()
     for f in fileList:
         date_stamp = f[15:-4]
         #problem is here that this for , finds d for first file and use it for all
         for line in fp :
              if date_stamp.startswith(line[:4]) :
                  d = int(line.split()[1])
         print d
         print "Processing file: " + str(f)
         fileWordList = []
         fileWordSet = set()
         # One word per line, strip space. No empty lines.
         fw = open(f, 'r')

         fileWords = Counter(w for w in fw.read().split()) 
         # For each unique word, count occurance and store in dict.
         for stemWord, stemFreq in fileWords.items():
             Freq= stemFreq / d
             if stemWord not in wordDict:
                 wordDict[stemWord] = [(date_stamp, Freq)]
             else:  
                 wordDict[stemWord].append((date_stamp, Freq))
这是可行的,但它给了我错误的输出,查找
d
的for循环只执行了一次,但我希望它针对每个文件运行,因为每个文件都有不同的
d
。我不知道如何为每个文件或我应该使用的任何其他文件更改此设置,以便获得正确的
d


非常感谢您的建议。

我不太明白您想做什么,但是如果您想对
fp
中的每一行“好”进行处理,您应该在
if
下移动相应的代码:

def parsing():
     fileList = pathFilesList()
     for f in fileList:
         date_stamp = f[15:-4]
         #problem is here that this for , finds d for first file and use it for all
         for line in fp :
             if date_stamp.startswith(line[:4]) :
                 d = int(line.split()[1])
                 print d
                 print "Processing file: " + str(f)
                 fileWordList = []
                 fileWordSet = set()
                 ...

您应该说明“for line in fp”循环只执行一次的原因,因为您每次都在一个相同的文件对象上循环-您正在使用文件中的所有行,而从未重置/重新创建文件迭代器。请使用“fp=open('yearTerm.txt').readlines()”来解决此问题。@Rawing非常感谢您。这起作用了,我没有意识到那个错误。