在Python 3.6中获取replace()的错误

问题描述 投票:1回答:1

我运行这个脚本时遇到2个错误(python3.6)。我试图解决这个问题,但我无法理解错误本身。我只是个初学者。

import random
from urllib.request import urlopen
import sys

WORD_URL = "http://learncodethehardway.org/words.txt"
WORDS = []

PHRASES = {
    "class %%%(%%%)":
        "Make a class named %%% that is-a %%%.",
    "class %%%(object):\n\tdef __init__(self. ***)":
        "class %%% has-a __init__ that takes self and *** parameters.",
    "class %%%(object):\n\tdef ***(self, @@@)":
        "class %%% has-a function named *** that takes self and @@@ parameters.",
    "*** = %%%()":
        "Set *** to an instance of class %%%.",
    "***.***(@@@)":
        "From *** get the *** function, and call it with parameters self, @@@",
    "***.*** = '***'":
        "From *** get the *** attribute and set it to '***'."
}

# if they want to drill phrases first
PHRASE_FIRST = False
if len(sys.argv) == 2 and sys.argv[1] == "English":
    PHRASE_FIRST = True

# load up the words from the website
for word in urlopen(WORD_URL).readlines():
    WORDS.append(word.strip())


def convert(snip, phra):
    class_names = [w.capitalize() for w in
                   random.sample(WORDS, snip.count("%%%"))]
    other_names = random.sample(WORDS, snip.count("***"))
    results = []
    param_names = []

    for i in range(0, snip.count("@@@")):
        param_count = random.randint(1, 3)
        param_names.append(', '.join(random.sample(WORDS, param_count)))

    for sentence in snip, phra:
        result = sentence[:]

        # fake class names
        for var1 in class_names:
            result = result.replace("%%%", var1, 1)

        # fake other names
        for var2 in other_names:
            result = result.replace("***", var2, 1)

        # fake parameter lists
        for var3 in param_names:
            result = result.replace("@@@", var3, 1)

        results.append(result)

    return results


# keep going until they hit CTRL + D
try:
    while True:
        snippets = PHRASES.keys()
        random.choice(list(snippets))

        for snipp in snippets:
            phras = PHRASES[snipp]
            question, answer = convert(snipp, phras)

            if PHRASE_FIRST:
                question, answer = answer, question

            print(question)

            input(">>> ")
            print("ANSWER : %s\n\n" % answer)
except EOFError:
    print("\nBye")

错误如下:

Traceback (most recent call last):
  File "F:/GAUTAM/Droid/PycharmProjects/Python_HardWay/oop_test.py", line 75, in <module>
    question, answer = convert(snipp, phras)
  File "F:/GAUTAM/Droid/PycharmProjects/Python_HardWay/oop_test.py", line 52, in convert
    result = result.replace("%%%", var1, 1)
TypeError: replace() argument 2 must be str, not bytes

我尝试过做很多事情。但是,似乎没有任何效果。当我将问题和答案放在func convert中时,为什么会出现错误。我在一本书“学习Python,艰难的方式”中看到了这段代码。

该脚本在Python 2上。我试图用Python 3编写它。

python python-3.x pycharm
1个回答
0
投票

urlopen().readlines()返回字节对象,而不是字符串。您需要通过正确的编码解码它们。例如你的循环中的WORDS.append(word.decode("utf-8").strip()),你加载网站上的文字。 - 杰罗尼莫

© www.soinside.com 2019 - 2024. All rights reserved.