Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/307.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ssl/3.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_String - Fatal编程技术网

Python 对文本文件中的行进行迭代,返回行号和引用?

Python 对文本文件中的行进行迭代,返回行号和引用?,python,string,Python,String,我正在尝试编写这段代码,它可以作为排序索引,筛选文本文件并返回字符串出现的位置以及它们在哪一行。我越来越接近了,但是我的迭代遇到了一个问题,我不知道该怎么做 def index(fileName, wordList): infile = open(fileName,'r') i = 0 lineNumber = 0 while True: for line in infile: lineNumber += 1

我正在尝试编写这段代码,它可以作为排序索引,筛选文本文件并返回字符串出现的位置以及它们在哪一行。我越来越接近了,但是我的迭代遇到了一个问题,我不知道该怎么做

def index(fileName, wordList):

    infile = open(fileName,'r')

    i = 0
    lineNumber = 0
    while True:
        for line in infile:
            lineNumber += 1
            if wordList[i] in line.split():
                print(wordList[i], lineNumber)
        i += 1
        lineNumber = 0

fileName = 'index.txt'
wordList = eval(input("Enter a list of words to search for: \n"))

index(fileName,wordList)
我用通用术语填充了我的.txt文件,因此它看起来如下所示:

bird 
bird 
dog 
cat 
bird
当我输入字符串列表时,例如:

['bird','cat']
我得到以下输出:

Enter a list of words to search for: 
['bird','cat']
bird 1
bird 2
bird 5

所以它给了我列表中第一个字符串的术语和行号,但它不会继续到下一个字符串。有什么建议吗?如果我可以优化输出,将行号包含在单个打印中,我将不胜感激。

如果您尝试重复循环一个文件对象,第一次之后的任何尝试都将从文件末尾开始并立即停止。有几种方法可以处理这个问题;您可以将算法更改为一次遍历文件,也可以将文件内容保存到其他数据结构中,然后分析该数据结构而不是文件,或者可以使用
infle.seek(0)
在循环之间返回到文件的开头。

读取文件后,当前文件位置将更改。一旦文件位置到达文件末尾,读取文件将产生空字符串

您需要使用
file.seek
回放文件位置以重新读取文件

但是,与倒带不同,我更愿意按如下操作(在操作符中使用and
):

  • eval
    执行任意表达式。与其使用
    eval
    ,不如使用
    input().split()

由于当您到达文件末尾时,任何读取文件的尝试都将产生一个空字符串,因此您的程序将失败。克服此问题的一种方法是使用
file.readlines
并将行存储在列表中:

with open('test.txt') as f:
    wordInput = [input(), input()] #capture the input
    lines = f.readlines()
    for word in wordInput:
        counter = 0
        for line in lines:
            counter += 1
            if word in line:
                print(word, counter)
但是,这对于大型文件来说有点低效,因为它会将整个文件加载到内存中的缓冲区中。另一种方法是,您可以在各行之间循环,然后在完成后调用
file.seek(0)
。这样,搜索将返回到文件的开头,您可以再次对其进行重新oop。它是这样工作的:

>>> with open('test.txt') as f:
        for line in f:
            print(line)
        f.seek(0)
        for line in f:
            print(line)


bird 

bird 

dog 

cat 

bird
0 #returns the current seek position
bird 

bird 

dog 

cat 

bird
另外,正如@falsetru在他的回答中提到的,避免使用
eval(input)
,因为它会计算您输入的任何表达式,这会导致意外的输入问题。使用
something
分隔值,然后执行
wordList=input()。拆分(something)


希望这有帮助

有趣的是,谢谢你的回复我现在正在阅读关于enumerate()的文章,还在学习中。对输出优化有什么意见吗?i、 e.鸟类1,2,5。在迭代过程中似乎很难做到这一点?我现在正在做。@user2909869,用字典保存匹配项怎么样?(单词作为键,匹配的行(列表)作为值)感谢字典的想法,我对我的原稿做了一些细微的修改,使它能够启动并运行,但使用字典作为输出完成了这项工作。谢谢你的回复。我最终使用了您给我的seek函数,它帮助我修复了所有代码。再次感谢你!
>>> with open('test.txt') as f:
        for line in f:
            print(line)
        f.seek(0)
        for line in f:
            print(line)


bird 

bird 

dog 

cat 

bird
0 #returns the current seek position
bird 

bird 

dog 

cat 

bird