代码之家  ›  专栏  ›  技术社区  ›  Ausamah Hobbi

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

  •  0
  • Ausamah Hobbi  · 技术社区  · 2 年前

    我在这件事上已经坚持了几个小时了,似乎无法克服它。我只想找到一个单词在所附文本文件中弹出的所有不同时间以及它的位置。指数

    我认为将word和文本文件转换为列表可能会有所帮助,但遗憾的是。 这是我现在拥有的。这是我正在使用的文本文件的粘贴箱 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")
    
    1 回复  |  直到 2 年前
        1
  •  1
  •   constantstranger    2 年前

    下面是一种解决问题的方法:

    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]