[英]Locating a character in one text file, and replacing it with a character from another
到目前为止,我的代码...
f = open("words.txt","r")
words = f.read()
f = open("solved.txt","r")
solved = f.read()
f = open("clues.txt","r")
clues = f.read()
def importclues():
global clues
global words
z=0
for z in clues:
words.replace(clues[z[1]],clues[z[0]])
print(words)
所以我试图从clues.txt文件的每一行中提取第二个字符
A#
M*
N%
在words.txt文件中找到该字符
#+/084&"
#3*#%#+
8%203:
,1$&
!-*%
.#7&33&
#*#71%
&-&641'2
#))85
9&330*
然后将其替换为clues.txt文件中每行的第一个字母,以便用户更容易猜测剩余的符号/字母对。
不幸的是,我收到以下错误消息
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
importclues()
File "/Users/Alastair/Desktop/CA.py", line 70, in importclues
words.replace(clues[z[1]],clues[z[0]])
IndexError: string index out of range
任何帮助将非常感激 :)
-Alastair
f.read()
可能不是在这里使用的正确方法...使用f.readlines()
可以得到一个以每行为元素的数组。
使用f.read()
您正在读取f.read()
字符-不能在换行符处分隔!
clues是一个字符串,因此for z in clues
将一个字符放在z
。
f = open("words.txt","r")
words = f.read()
f = open("solved.txt","r")
solved = f.read()
f = open("clues.txt","r")
clues = f.readlines()
def importclues():
global clues
global words
for line in clues:
words.replace(line[1], line[0])
print(words)
这未经测试,但应该可以解决问题。 更改: read()
-> readlines()
和for循环
此代码没有错误检查-例如,您可以丢弃len(line) < 3
(包括换行符)的每一line
您应该使用:
clues = f.readlines()
它将占用每一行并转换为数组的索引。 所以:
words.replace(z[1], z[0])
会带您前进。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.