Python搜索文本中的项目

2024-10-02 22:34:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用Python编写一个脚本,它在文本文件中搜索各种项目,一旦找到该项目,它就会移动到下一个项目。在这种情况下,我找到了一个人,然后将物品归于此人。但现在的情况是,我不断地让第一个人重复出现在列表中的次数。我能够成功地用其他项目找到这个人以外,但似乎当谈到找到这个人,它重复。请看看我到目前为止有什么。我已经剥离了所有的工作,只是为了集中在这一个特定的问题。你知道吗

    text = open("Register.txt",'rt') #opens the Register text file
    Register = text.read()

    length = len(Register)
    lines = Register.splitlines() #Breaks the .txt file down into their own lines


    for line in lines: #searches each line for the following statement
        if line.find("Per End")!=-1:  #searches each line for the ("*") item and asks if it is True
            nameline = Register.index(line)
            namebegin = nameline-15
            print nameline
            print Register[namebegin:nameline]

文本中大约有60个人,此代码只列出前一个60次。每一个后面都是“每端”,这就是为什么我用它来查找文本中的人。从那里,它应该定位索引并减去一些项目,以确保整个名称输出。你知道吗


Tags: the项目texttxtregisterforifline