Python - 文件开头的文件中单词的位置

时间:2018-02-09 18:25:40

标签: python file search indexing position

我希望从文件开头的文件中获取单词的位置。在计算位置时,它应该计算\ n,\ r,\ t。我尝试索引并查找命令,但它们在单独的行上工作,并且从一开始就不提供位置。有人可以建议什么吗?我写了下面的代码:

def findword(filename:str, word:str):
    try:
        file = open(filename, 'r')
        count = 0
        occurances = []
        for line in file:
            if word in line:
                print("word found")
                occurance = line.find(word)
                occurances.append(occurance)
                print(occurance)
                count = count + 1
                print(count)
        occurances.sort()
        print(occurances)
        if count == 0:
            print("word not found")
    except FileNotFoundError:
        print("warning: file not found")
        return -1

谢谢。

0 个答案:

没有答案