【问题标题】:Locating a character in one text file, and replacing it with a character from another在一个文本文件中定位一个字符,并用另一个字符替换它
【发布时间】:2014-02-15 13:17:09
【问题描述】:

到目前为止我的代码...

    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)

所以我试图从线索.txt 文件中的每一行中取出第二个字符

A#
M*
N%

在 words.txt 文件中找到该字符

#+/084&"
#3*#%#+
8%203:
,1$&
!-*%
.#7&33&
#*#71%
&-&641'2
#))85
9&330*

然后将其替换为线索.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

任何帮助将不胜感激:)

-阿拉斯泰尔

【问题讨论】:

  • 首先做一个print(z)print(clues),看看变量是什么。这通常是调试的第一步。

标签: python python-3.x text-files decode encode


【解决方案1】:

f.read() 可能不适合在这里使用...使用f.readlines() 你会得到一个数组,其中每一行都作为一个元素。

使用f.read(),您正在阅读一大串字符 - 没有在换行符处分隔!

clues 是一个字符串,所以for z in cluesz 中放入一个字符。

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 循环

此代码没有错误检查 - 例如,您可以丢弃每个 line 其中 len(line) &lt; 3(包括换行符)

【讨论】:

    【解决方案2】:

    你应该使用:

    clues = f.readlines()
    

    它将获取每一行并转换为数组的索引。所以:

    words.replace(z[1], z[0])
    

    会让你向前迈出一步。

    【讨论】:

    • 我很抱歉,但我似乎仍然无法让它工作。它会打印三次 words.txt 文件,因为这是线索文件中的行数。请帮忙,否则有人会冲我大喊大叫:(
    猜你喜欢
    • 2013-06-26
    • 2019-03-21
    • 1970-01-01
    • 2020-02-08
    • 2018-05-19
    • 2011-08-21
    • 1970-01-01
    • 1970-01-01
    • 2021-06-15
    相关资源
    最近更新 更多