Vim : how to index a plain text file?

眉间皱痕 提交于 2019-11-29 11:22:39

I took the liberty of writing the following function, based on using the :g/STRING/# command to get the matches. I read the results of this command into a list, and then process it to return a list of matching line numbers:

function! IndexByWord( this_word )
    redir => result
    sil! exe ':g/' . a:this_word . '/#'
    redir END
    let tmp_list = split(strtrans(result),"\\^\@ *")
    let res_list = []
    call map(tmp_list, 'add(res_list,matchstr(v:val,"^[0-9]*"))')
    let res = a:this_word . ' : ' . string(res_list)
    let res = substitute(res, "[\\[\\]\\']", "", "g")
    echo res
endfunction

So you could call this function on all the words you wish (or write a script to do so) and direct the output to a file. Not very elegant, perhaps, but nicely self-contained.

Hope this helps, rather than hinders.

Here is a revised version of the function posted by Prince Goulash. This version takes a list of words as input and returns a formatted and alphabetized string of the result:

function! IndexByWord( wordlist )
    let temp_dict = {}
    for word in a:wordlist
        redir => result
        sil! exe ':g/' . word . '/#'
        redir END
        let tmp_list = split(strtrans(result),"\\^\@ *")
        let res_list = []
        call map(tmp_list, 'add(res_list,str2nr(matchstr(v:val,"^[0-9]*")))')
        let temp_dict[word]  = res_list
    endfor
    let result_list = []
    for key in sort(keys(temp_dict))
        call add(result_list, key . ' : ' . string(temp_dict[key])[1:-2])
    endfor
    return join(result_list, "\n")
endfunction

One way to call it would be:

echo IndexByWord(['word1', 'word2', 'word3', etc])

There should be no problem with having a long list of words, although in that case you would probably want to use a list variable and getting the results would of course take more time. For example:

let my_word_list = ['word1', 'word2', . . . 'word1000']
echo IndexByWord(my_word_list)

Have a look at ptx, perhaps

:%!cut -d: -f2 | ptx -Ar

Will output something like this, when unmodified:

:1:                         London,   Berlin, Paris
:2:               New-York, London,   Berlin
:1:                                   London, Berlin, Paris
:2:                       New-York,   London, Berlin
:2:                                   New-York, London, Berlin
:4:                                   New-York, Paris
:1:                 London, Berlin,   Paris
:4:                       New-York,   Paris
:2:                            New-   York, London, Berlin
:4:                            New-   York, Paris

I'll see if I can the rest of the steps too

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!