Python中列表中的隐藏词

0 投票
1 回答
1024 浏览
提问于 2025-04-18 10:24

我有一个函数,它可以从一段文本中生成一个列表的列表。我希望这个函数能够在这些列表中找到一个单词,比如“noir”,无论是横着找还是竖着找,并返回这个单词的位置坐标,具体如下:

  • row_start 是单词第一个字母所在的行号。
  • column_start 是单词第一个字母所在的列号。
  • row_end 是单词最后一个字母所在的行号。
  • column_end 是单词最后一个字母所在的列号。

这是我目前的代码:

def checkio(text, word):
    rows = []
    col = []
    coordinates = [] 
    word = word.lower()
    text = text.lower()
    text = text.replace(" ", "")
    text = text.split("\n")
    for item in text:
        rows.append([item]) #Creates a list of lists by appending each item in brackets to list.

上面函数的示例输出:

   [['hetookhisvorpalswordinhand:'], 
    ['longtimethemanxomefoehesought--'], 
    ['sorestedhebythetumtumtree,'], 
    ['andstoodawhilei**n**thought.'], 
    ['andasinuffishth**o**ughthestood,'], 
    ['thejabberwock,w**i**theyesofflame,'], 
    ['camewhifflingth**r**oughthetulgeywood,'], 
    ['andburbledasitcame!']]

在这个例子中,“noir”的坐标是 [4, 16, 7, 16]。 row start 是第 4 行, column start 是第 16 列, row end 是第 7 行, column end 是第 16 列。

这个单词可以横着或竖着找到,但不能反向查找。

1 个回答

0

虽然不是特别完美,但回答了问题.. :-) 我把这个做成了一个字符串列表。这部分需要在代码中提前处理好。

words = [
    'hetookhisvorpalswordinhand:',
    'longtimethemanxomefoehesought--',
    'sorestedhebythetumtumtree,', 
    'andstoodawhileinthought.',
    'andasinuffishthoughthestood,',
    'thejabberwock,witheyesofflame,', 
    'camewhifflingthroughthetulgeywood,',
    'andburbledasitcame!'
]

word = 'noir'

print [[row+1, line.find(word)+1, row+1, line.find(word)+len(word), line] for row, line in enumerate(words) if line.find( word ) >= 0]

words_transp = [''.join(t) for t in zip(*words)]

print [[line.find(word)+1, col+1, line.find(word)+len(word), col+1, line] for col, line in enumerate( words_transp ) if line.find( word ) >= 0]

输出结果是:

[[4, 16, 7, 16, 'sotnoira']]

注意,这里没有进行很多错误检查。这是给提问者的一个练习。:-)

顺便提一下,你需要注意计数的问题,因为在Python中,计数是从0开始的,所以这里有一些"+1"。

撰写回答