python - 打印文本文档中的特定字母以显示消息?
问题描述
我正在尝试创建一个函数,该函数将从文本文档中提取字母,并将这些字母附加到一个列表中,该列表将被打印出来以显示一条消息。它给了我一个无效的语法,但我不知道该怎么写。
这是我到目前为止所拥有的
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()
如果重要的话,这里是文本:
他们喜欢苹果。
我喜欢梨。
早餐时间。
请上燕麦片。
给服务员小费。
解决方案
除了 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
推荐阅读
- javascript - 如何为表单中的不同选项组合生成不同的表格 [HTML/JS]
- angular - 更新 formArray 而不发出 valueChanges
- php - 无法连接到登录页面的数据库(PHP,MYSQL)
- javascript - Axios - 参数 - 在引号“paramvalue”中传递参数值的问题
- laravel - Laravel 7 - 集合分页
- python - tkinter.TclError:无效的命令名称“.!canvas”
- nestjs - Typeorm - 转换响应
- java - 从 Kotlin 到 Java
- arrays - Matlab:仅对特定字符数组执行过程
- for-loop - 变量仅在 FOR 循环结束时设置,然后在下一次运行时挥之不去