在充满随机字母的文本文件中查找随机单词的位置

Finding a position of a random word in a text file full of random letters

我已经被困在这个问题上几个小时了,似乎无法破解它。我只想找到一个单词在附加的文本文件中弹出的所有不同时间及其 location.index.

我认为将单词和文本文件转换为列表可能会有所帮助,但唉。 这就是我现在所拥有的。这是我正在使用的文本文件的粘贴箱 https://pastebin.com/MtjkvHaf

import string
import random
import os.path
def findWord(filename:str, word:str):
    if os.path.isfile(filename) == True:
        f = open(filename, 'r')
        fStr = str(f.read())
        location = []
        charList = []
        wordList = []
        i = 0
        j = 0

        #converts word to list
        for l in word:
            wordList.append(l)
    
        #converts text file to list
        for line in fStr:
            for c in line:
                charList.append(c)
        
        
        for i in charList:
            if wordList[0] == charList[i]:
                pos = i
                location.append(pos)
        print(location)
       
                
    else:
    print("File not found")
    
findWord("random_letters_05292022_1902.txt", "potato")

这里有一种方法可以完成您的问题:

import re
import os.path
def findWord(filename:str, word:str):
    if not os.path.isfile(filename):
        print("File not found")
        return
    with open(filename, 'r') as f:
        fStr = str(f.read())
        locs = []
        loc = 0
        while loc != -1:
            loc = fStr.find(word, locs[-1] + len(word) if locs else 0)
            if loc != -1:
                locs.append(loc)
        print(locs)

findWord('foo.txt', 'foo')

输入文件foo.txt:

barbarfoobarbarbarfoobarbarbarfoobar
barbarfoobarbarbarfoobarbarbarfoobar
barbarfoobarbarbarfoobarbarbarfoobar
barbarfoobarbarbarfoobarbarbarfoobar
barbarfoobarbarbarfoobarbarbarfoobar
barbarfoobarbarbarfoobarbarbarfoobar

输出:

[6, 18, 30, 43, 55, 67, 80, 92, 104, 117, 129, 141, 154, 166, 178, 191, 203, 215]