查找文件中重复单词的索引

时间:2017-04-24 23:12:27

标签: python file directory

我正在尝试编写一个函数来查找文件中字符串的索引位置。 为了做到这一点,我想在文件中的每一行上循环迭代。 现在该文件名为words.txt,包含:

hello
hi
hello
hi
hi

如果我把' hi'作为一个参数,我希望我的代码打印1,3,4

截至目前,这是我的代码:

def line(word, filename):
    f=open (filename, 'r')
    for (i , line) in enumerate (f):
        if word in line:
            return  i

截至目前,我的代码可以正常工作,但只打印出1而不是多个值。 我猜这与我的枚举函数有关。 有人可以帮我吗?

4 个答案:

答案 0 :(得分:1)

当您return一个值时,您的功能会立即退出。 print语句没有此效果。 (如果您确实想要返回多个值,可以尝试将它们附加到列表中,并在遍历每一行后返回列表。)

答案 1 :(得分:1)

包含列表理解的版本:

<div id="wrapper">
<div style="max-width:900px;margin: 0 auto;">
<div style="width:100%;">


<div style="float:left;"><img src="img" width="250" height="150" ><br>This text goes under the Picture.</div>
<div style="float:left;"><img src="img" width="250" height="150" ><br>This text goes under the Picture.</div>
<div style="float:left;"><img src="img" width="250" height="150" ><br>This text goes under the Picture.</div>
<div style="float:left;"><img src="img" width="250" height="150" ><br>This text goes under the Picture.</div>
<div style="float:left;"><img src="img" width="250" height="150" ><br>This text goes under the Picture.</div>
<div style="float:left;"><img src="img" width="250" height="150" ><br>This text goes under the Picture.</div>
<div style="float:left;"><img src="img" width="250" height="150" ><br>This text goes under the Picture.</div>

</div>
</div>

</div>


#wrapper{

    margin: 0 auto;
        width: 900px;
    max-width: 100%;
    box-sizing: border-box;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
}

答案 2 :(得分:0)

def line(word, filename):
    f = dict(list(enumerate(open(filename,'r'))))
    for k in f:
        if word in f[k]:
            print (k)

答案 3 :(得分:0)

如果你需要找到确切的单词(不是单词中另一个单词的一部分),你应该使用空白符号&#39;来分隔单独的单词。 &#39;并比较单词。检查字符串中单词的出现次数:

import os

def list_of_indexes(word, filename):
    """ Return list of indexes with encounter of word in the line number """
    lst = []
    if not os.path.isfile(filename):  # file doesn't exist
        print('File does not exist')
        return lst  # return empty list
    f = open(filename, 'r')  # open file for reading
    for (i, line) in enumerate(f):
        if word in line:
            lst.append(i)
    f.close()  # close file before exit
    return lst

print(list_of_indexes('hi', 'filename.txt'))

对于&#39; filename.txt&#39;:

hello
hi
hello
hi
hi
how are you
fine
Hitchhaker
thanks
anchithere
ship

它将返回:

D:\>python list_of_indexes.py
[1, 3, 4, 9, 10]
相关问题