首页 > 解决方案 > 打印文本文档中的特定字母以显示消息?

问题描述

我正在尝试创建一个函数,该函数将从文本文档中提取字母,并将这些字母附加到一个列表中,该列表将被打印出来以显示一条消息。它给了我一个无效的语法,但我不知道该怎么写。

这是我到目前为止所拥有的

def decodefile():
        codeKey = [[0, 1, 2, 4, 7, 14], [5], [1, 16], [7,8], [14,18]]
        decoded = []
        with open("sentences.txt") as fr:
            listLine = [ch for ch in line]
            for x in range(0, len(listLine)
                if (x.index in codeKey):
                    decoded.append(x)
                    print(decoded)

decodefile()

如果重要的话,这里是文本:

他们喜欢苹果。

我喜欢梨。

早餐时间。

请上燕麦片。

给服务员小费。

标签: python

解决方案


除了 for 循环前面明显缺少括号外,您还缺少一些其他内容。

def decodefile():
        codeKey = [[0, 1, 2, 4, 7, 14], [5], [1, 16], [7,8], [14,18]]
        decoded = []
        with open("sentences.txt") as fr:
            # Keep track of which line you are on
            line_no = 0
            # Iterate over each line in the file
            for line in fr:
                listLine = [ch for ch in line]
                for x in range(0, len(listLine)):
                    # check the appropriate code key, not the whole list
                    if (x in codeKey[line_no]):
                        decoded.append(listLine[x])
                        print(decoded)
                # Move to the next line
                line_no +=1

decodefile()

这将产生以下输出:

['T']
['T', 'h']
['T', 'h', 'e']
['T', 'h', 'e', ' ']
['T', 'h', 'e', ' ', 'k']
['T', 'h', 'e', ' ', 'k', 'e']
['T', 'h', 'e', ' ', 'k', 'e', 'o']
['T', 'h', 'e', ' ', 'k', 'e', 'o', 'i']
['T', 'h', 'e', ' ', 'k', 'e', 'o', 'i', 's']
['T', 'h', 'e', ' ', 'k', 'e', 'o', 'i', 's', 'h']
['T', 'h', 'e', ' ', 'k', 'e', 'o', 'i', 's', 'h', 'e']
['T', 'h', 'e', ' ', 'k', 'e', 'o', 'i', 's', 'h', 'e', 'r']
['T', 'h', 'e', ' ', 'k', 'e', 'o', 'i', 's', 'h', 'e', 'r', 'e']

您还可以''.join(decoded)在最后添加将其连接成一个字符串,这将给出:

The keoishere

推荐阅读