0
이 스크립트 (python3.6)를 실행할 때 오류가 2 번 발생합니다. 문제를 해결하기 위해 노력했지만 오류 자체를 이해할 수는 없습니다. 나는 이것의 초보자에 불과하다. 다음과 같이Python 3.6에서 replace() 오류 발생
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로 변환 할 때 질문과 답변을 넣을 때 오류가 발생하는 이유는 무엇입니까? 이 코드는 "Python 배우기, 어려운 길"이라는 책에서 보았습니다.
스크립트는 내가
'urlopen(). readlines()'는 문자열이 아닌'bytes' 객체를 반환합니다. 올바른 인코딩을 통해 디코딩해야합니다. 예를 들어,'WORDS.append (word.decode ("utf-8"). strip())'루프에서'# 웹 사이트의 단어를로드합니다. ' – Jeronimo
효과가있었습니다! 고마워요! –
FWIW, SO Python 대화방 일반인 [LPTHW 권장하지 않음] (http://sopython.com/wiki/LPTHW_Complaints). 그것이 효과가 있다면 좋겠지 만이 책에는 몇 가지 문제가 있음을 기억하십시오. 파이썬 3을 목표로하는 튜토리얼을 사용하는 것을 고려해야합니다. [튜토리얼을 읽어야 할 대상은 무엇입니까?] (https://sopython.com/wiki/What_tutorial_should_I_read%3F) –